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
8
  • new_df <- get(df.str); new_df$x1 <- 0 Commented Jun 8, 2018 at 3: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. Commented Jun 8, 2018 at 3: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 link to the already marked dupe. Commented Jun 8, 2018 at 3:27
  • @RonakShah - sure, that might cover it off more cleanly. Commented Jun 8, 2018 at 3:34
  • 1
    @ZhenduoCao - `[<-` is essentially just df["var"] <- 1 put back into functional form - `[<-`(df, "var", 1) Commented Jun 8, 2018 at 3:37

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that is helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.