0

I want to be able to be able to create a new variable in a data.frame that is named based on an existing string. So, for example, if the new variable is Q7A what I have tried to do is the following:

question <- "Q7A"
Q <- parse( text = paste("data$", question, sep = ""))
eval(Q) <- 3

What I want this to be interpreted as is:

data$Q7A <- 3

But I get the following error message: Error in eval(Q) <- 3 : could not find function "eval<-"

Thomas
  • 43,637
  • 12
  • 109
  • 140
Michael
  • 13,244
  • 23
  • 67
  • 115
  • 1
    Are you doing a course that has this as a problem? Suspiciously similar to the question I link to as possible duplicate. – Gavin Simpson Jul 22 '13 at 19:17

1 Answers1

3

Don't use $.

data[,question] <- 3

Always remember fortune(106):

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)
joran
  • 169,992
  • 32
  • 429
  • 468
  • Even more eccentric: Computing what data.frame() is assigned to, e.g. using `my.df <- "iris"; question <- "newcol"; answer <- 42; assign(my.df,"$<-"(eval(parse(text=my.df)),question,answer))`... ;) – texb Jul 22 '13 at 19:17