如何在R中将字符串转换为赋值语句?

时间:2019-04-29 00:59:53

标签: r eval paste

列表中有很多列。我想使用一些功能来自动工作。

我有一个data.frame myData

没有myData$home_player_X。我正在手动一个接一个地添加它。

如果我手动执行此操作,则代码如下所示:

myData$home_player_1 <- lDataFrames[[3]]$home_player_1
myData$home_player_2 <- lDataFrames[[3]]$home_player_2
...
myData$home_player_11 <- lDataFrames[[3]]$home_player_11

如果仅考虑<-之后的部分,我可以将其转换为表达式:

eval(parse(text=paste("lDataFrames[[3]]$home_player_",i,sep="")))

但是我想转换整个字符串。整个字符串是这样的:

paste("myData$home_player_",i," <- lDataFrames[[3]]$home_player_", i,sep="")

我想将字符串转换为赋值语句,因此可以在for循环中完成

2 个答案:

答案 0 :(得分:1)

您可以直接在mydata中复制所需的列,而不必使用字符串。

cols <- grep("^home_player", names(lDataFrames[[3]]), value = TRUE)
mydata[cols] <- lDataFrames[[3]][cols]

使用可复制的示例,

df <- data.frame(home_player_1 = 1:5, home_player_2 = 6:10, home_player_3 = 11:15)
cols <- grep("^home_player", names(df), value = TRUE)
mydata <- data.frame(matrix(nrow = nrow(df), ncol = length(cols), 
          dimnames = list(NULL, cols)))
mydata[cols] <- df[cols]

mydata
#  home_player_1 home_player_2 home_player_3
#1             1             6            11
#2             2             7            12
#3             3             8            13
#4             4             9            14
#5             5            10            15

答案 1 :(得分:0)

不要使用$表示法,只需将变量名用作索引即可。我用Y代替了lDataFrames[[3]],但翻译起来应该很容易。

myData = data.frame(Var1 = 1:10)
Y = data.frame(home_player_1 = 11:20, 
    home_player_2 = 21:30, home_player_3 = 31:40)

for(i in 1:3) {
    VarName = paste0("home_player_", i)
    myData[ ,VarName] = Y[ ,VarName]
}

myData
   Var1 home_player_1 home_player_2 home_player_3
1     1            11            21            31
2     2            12            22            32
3     3            13            23            33
4     4            14            24            34
5     5            15            25            35
6     6            16            26            36
7     7            17            27            37
8     8            18            28            38
9     9            19            29            39
10   10            20            30            40