我试图在数据框中创建一堆列,其名称取决于两个向量中的值。我会尽力解释并提供示例数据,但对于任何不确定之处,我们会提前道歉。
# my data frame
df <- data.frame(id = c(1, 2, 3), var1 = c("a", "c", "e"), var2 = c("b", "d", "f"))
# the two vectors
v1 <- c("x", "y", "z")
v2 <- c(10, 20, 30)
然后我想做这样的事情:
for (i in 1:length(v1)) {
for (j in 1:length(v2)) {
dataset$v1[i]_v2[j] <- "some value"
}
rm(j)
}
rm(i)
当然,这种方法行不通的棘手部分是dataset$v1[i]_v2[j]
。但是也许有某种方法可以解决此问题?我将不胜感激!
答案 0 :(得分:1)
您可以像这样进行分配:
for (i in 1:length(v1)) {
for (j in 1:length(v2)) {
# use [[]] to access the column
df[[paste(v1[i], v2[j], sep='_')]] <- "some value"
# this would also work:
# df[, paste(v1[i], v2[j], sep='_')] <- "some value"
}
rm(j)
}
rm(i)
如果您真的想用"some_value"
填充所有列,这甚至会更加容易:
column.names <- as.vector(sapply(v1, function(x) paste(x, v2, sep='_')))
df[,column.names] <- 'some_value'