R:在循环内动态调用变量

时间:2018-11-16 18:57:46

标签: r loops environment-variables

我需要在循环中调出变量并将其用作我的列名:

这是一个示例数据集:

mtcars.df <- mtcars

预期输出:

mtcars.df <- mtcars.df %>% add_column(a1 = sample (1:4, 32, replace = TRUE), b1 = sample (1:4, 32, replace = TRUE), c1 = sample (1:4, 32, replace = TRUE))

因此,需要在循环中创建a1,b1和c1,并将其重命名为a1,b1和c1。在原始数据集中,名称更长(和不同的组合),但这是在变量mpg.filename中定义的。

这是到目前为止我一直在尝试的:第一种显然不能给出理想的结果,而只是显示我想要实现的目标。

mpg.filename <- c("a1.file", "b1.file", "c1.file")
for (i in mpg.filename) {
  sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
  mtcars.df$i <- sample (1:4, 32, replace = TRUE)
}

for (i in mpg.filename) {
  sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
  mtcars.df$temp.var <- sample (1:4, 32, replace = TRUE)
  temp.name <- paste0 (sample.name) %>% rlang::parse_expr()
  mtcars.df <- mtcars.df %>% rename (eval (sample.name) = temp.var)
}

for (i in mpg.filename) {
  sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
  mtcars.df$temp.var <- sample (1:4, 32, replace = TRUE)
  temp.name <- paste0 (sample.name) %>% rlang::parse_expr()
  mtcars.df <- mtcars.df %>% rename (syms(sample.name) = temp.var)
}

我也尝试过getas.symbolparse (text = "sample.name"),但也没有用。

感谢您的帮助。我曾尝试在论坛上查看其他答案,但它们似乎并不适用或起作用。

using eval() on string to access object attributes in R

call columns from inside a for loop in R

Getting strings recognized as variable names in R

How to evaluate an expression with variables in R?

2 个答案:

答案 0 :(得分:4)

您的第一次尝试已接近!当您想使用字符访问/创建data.frame中的列时,需要使用[[而不是$。如果您只需要这样做,就不需要符号/解析/其他复杂的废话。

for(i in mpg.filename) {
  sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
  mtcars.df[[sample.name]] <- sample(1:4, 32, replace=TRUE)
}

答案 1 :(得分:3)

让我知道这是否成功了-

mpg.filename <- c("a1.file", "b1.file", "c1.file")
for (i in 1:length(mpg.filename)) {
  sample.name <- unlist(strsplit(as.character(mpg.filename[i]), '.', fixed = TRUE))[1]
  mtcars.df$i <- sample (1:4, 32, replace = TRUE)
  colnames(mtcars.df)[length(mtcars.df)]<-paste(sample.name)
}