1

Now I have a data frame which is defined as below.

df=data.frame(x1=c(1,2,3),x2=c(4,5,6))

And I only have the string variable of that data.frame

df.str = 'df'

How to change a column of df (say, assign 0 to df$x1) without using variable name df? Only df.str is allowed therefore you can't write df$x1=0.

I tried a lot of ways but none of them worked:

df.str$x1=0
df.str[[x1]]=0
df.str[,'x1']=0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Zhenduo Cao
  • 151
  • 1
  • 3
  • `new_df <- get(df.str); new_df$x1 <- 0` – Ronak Shah Jun 08 '18 at 03:03
  • 1
    @RonakShah - it's very close but not sure if a duplicate, given that this is also talking about assignment of a variable within the referenced data.frame. – thelatemail Jun 08 '18 at 03:15
  • @thelatemail I think the main objective of the question is to know `get` or `mget`, once OP gets it, it is pretty easy to replace the column value with 0. I could add [this](https://stackoverflow.com/questions/19295277/replacing-a-whole-column-in-r) link to the already marked dupe. – Ronak Shah Jun 08 '18 at 03:27
  • @RonakShah - sure, that might cover it off more cleanly. – thelatemail Jun 08 '18 at 03:34
  • @RonakShah Actually what I didn't know is the operation '[<-' – Zhenduo Cao Jun 08 '18 at 03:35
  • 1
    @ZhenduoCao - `\`[<-\`` is essentially just `df["var"] <- 1` put back into functional form - `\`[<-\`(df, "var", 1)` – thelatemail Jun 08 '18 at 03:37
  • @ZhenduoCao just do `get` on your `df.str` and store it a new variable and then try any of the operation which you already tried. – Ronak Shah Jun 08 '18 at 03:39
  • Creating a new variable defeats the purpose and it is not what the OP asked about – akrun Jun 08 '18 at 03:39

1 Answers1

1

We need get to get the value and assign to assign the values

get(df.str)
assign(df.str, `[<-`(get(df.str), "x1",  value = 0))

Now, if we check 'df', the 'x1' column is assigned to 0

df
#  x1 x2
#1  0  4
#2  0  5
#3  0  6
akrun
  • 874,273
  • 37
  • 540
  • 662