简体   繁体   English

在数据框中,使用R中向量的名称创建列

[英]In data frame, create columns with names from vector in R

I am trying to create a bunch of columns in a data frame with their names dependent on values in two vectors. 我试图在数据框中创建一堆列,其名称取决于两个向量中的值。 I will do my best to explain and provide sample data but do apologize in advance for any unclarity. 我会尽力解释和提供示例数据,但对于任何不确定之处,我们会提前道歉。

# 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)

I would then like to do something like this: 然后,我想做这样的事情:

for (i in 1:length(v1)) {
  for (j in 1:length(v2)) {
    dataset$v1[i]_v2[j] <- "some value"
  }
  rm(j)
}
rm(i)

Of course the tricky part in which this approach won't work is dataset$v1[i]_v2[j] . 当然,这种方法不起作用的棘手部分是dataset$v1[i]_v2[j] But is there maybe some way to work around this? 但是也许有某种方法可以解决此问题? I would be grateful for any help! 我将不胜感激!

You can do the assignment like this: 您可以像这样进行作业:

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)

In case you literally want to fill all columns with "some_value" this is even easier: 如果您真的想用"some_value"填充所有列,这会更加容易:

column.names <- as.vector(sapply(v1, function(x) paste(x, v2, sep='_')))
df[,column.names] <- 'some_value'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM