Eric
Eric

Reputation: 23

How to convert a string into assignment statement in R?

There are many columns in the list. I'd like to use some functions to work automatically.

I have a data.frame myData

There is no myData$home_player_X. I'm adding it one by one manually.

If I do it manually, the code looks like this:

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

If we only consider the part after <-, I can convert it into an expression:

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

But I want to convert whole string. The whole string is this:

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

I want to convert string into an assignment statement, so I can do it in a for loop

Upvotes: 2

Views: 120

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

Instead of playing with strings, you can directly copy the required columns in mydata.

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

Using reproducible example,

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

Upvotes: 1

G5W
G5W

Reputation: 37641

Instead of using the $ notation, just use the variable name as an index. I am substituting Y for your lDataFrames[[3]], but it should be easy to translate.

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

Upvotes: 0

Related Questions