user2543622
user2543622

Reputation: 6766

R convert character to dataframe column name and then replace values in a column

I was able to get content of the column pointed by character variable b. But i want to make column emp 0. How could i do that?

emp=c(1,2,30)
abc=data.frame(emp)
b="emp"
#below line gives content of column emp
eval(parse(text=paste("abc$", b, sep = "")))
#how can i replace each value in column emp with 0?
#below line doesnt work :(. It runs without error but values dont change 
assign((text=paste("abc$", b, sep = "")),0)
abc

Upvotes: 0

Views: 2305

Answers (2)

MrFlick
MrFlick

Reputation: 206232

There is almost never a good reason to use eval(parse()). The $ syntax should only be used when you know the exactly name you want to extract. If you want to specify that value with a variable, use the [,] indexing method. For example

abc[, b] <- 0

or

abc[[b]] <- 0

The crazy assign doesn't work because abc$b isn't a variable. This is actually a function call similar to '$'(abc, "b"). You need to pass in the name of a variable to assign, not an expression.

Upvotes: 0

Marat Talipov
Marat Talipov

Reputation: 13304

Besides trivial abc[,'emp'] <- 0, you can do:

eval(parse(text=sprintf('%s$%s <- 0','abc',b)))

abc
#  emp
#1   0
#2   0
#3   0

Upvotes: 1

Related Questions