问题
I am trying to assign a column of data to a new column in an existing data frame. The data frame changes in a loop, from scores.d, to scores.e. My desired output is to have scores.X$new.col populated with the vals, where X is replaced with the current dfname.
dfnames <- c("d","e")
scores.d <- data.frame(x = 1, y = 1:10)
scores.e <- data.frame(x = 2, y = 10:20)
vals <- 60:70
for (i in seq_along(dfnames)){
assign(get(paste0("scores.",dfnames[i]))$new.col,vals)
}
Error in assign(get(paste0("scores.", dfnames[i]))$new.col, vals) :
invalid first argument
This gives me an error, because assign is looking for a character string as the first argument, when I need it to include the column name. Simply adding $new.col to the paste command doesn't work (assume $ doesn't translate from string).
I am new to R and don't know the dos and don'ts of assigning things. I thought to make a list of data frames, then populate each with vals, but it didnt work as I am specifying particular columns, in my real data, the data frames are pre-existing anyway, I'm just trying to add to them here. Thoughts?
EDIT*
@Jason has provided an answer, by allocating the values to a temporary variable, then assigning it back. Works fine for my purposes, however I had tried it with a list of strings in place of creating the names via paste0()
, and it still gave me the error. First, Jason's working answer:
dfnames <- c("d","e")
scores.d <- data.frame(x = 1, y = 1:10)
scores.e <- data.frame(x = 2, y = 11:20)
vals <- 61:70
for (i in dfnames){ #don't need seq_along
dat<-get(paste0("scores.",i)) #pull up the data
dat$new.col<-vals
assign(paste0('scores.',i),dat) #replace old data frame with new
}
Now with a list of names replacing the paste procedure (note the change to seq_along):
dfnames <- c("d","e")
scores.d <- data.frame(x = 1, y = 1:10)
scores.e <- data.frame(x = 2, y = 11:20)
vals <- 61:70
# for demonstrative purposes only, these were created in a loop in my code
full.dfnames[1] <- "Scores.d"
full.dfnames[2] <- "Scores.e"
for (i in seq_along(dfnames)){ #added seq_along back for the name index
dat<-get(full.dfnames[i]) #pull up the data
dat$new.col<-vals
assign(full.dfnames[i],dat) #replace old data frame with new
}
>Error in assign(get(paste0("scores.", dfnames[i]))$new.col, vals) :
invalid first argument
回答1:
I believe the following works though might not be as streamlined as you would like.
dfnames <- c("d","e")
scores.d <- data.frame(x = 1, y = 1:10)
scores.e <- data.frame(x = 2, y = 11:20)
vals <- 61:70
for (i in dfnames){ #don't need seq_along
dat<-get(paste0("scores.",i)) #pull up the data
dat$new.col<-vals
assign(paste0('scores.',i),dat) #replace old data frame with new
}
来源:https://stackoverflow.com/questions/28891156/assign-to-a-variable-data-frame-in-r