从数据框的元素中分配变量

时间:2014-10-21 16:33:37

标签: r

我有一个数据框,对于每一行,我想从变量名称部分创建一个变量并为其分配相应的值,这样我最终会得到三个变量(variable1< - “c”等)

d <- data.frame(
  variable_name = c("variable1", "variable2", "variable3"), 
  variable_value = c("c", "a", "b")
)

目前我能想到的唯一方法就是手动列出我想要拿出的每一行

variable1 <- subset(d,variable_name == "variable1")[1,2]
variable2 <- subset(d,variable_name == "variable2")[1,2]
variable3 <- subset(d,variable_name == "variable3")[1,2]

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

尝试:

 list2env(setNames(as.list(as.character(d$variable_value)),
                                 d$variable_name), envir=.GlobalEnv)

  variable1
  #[1] c

  variable2
  #[1] "a"