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
  • 355,584
  • 18
  • 123
  • 178
Zhenduo Cao
  • 41
  • 1
  • 3

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
  • 789,025
  • 32
  • 460
  • 575