0

I have string variable, str, with the value "car". I would like to create a new column in my data frame using str, but creates a column with the name "car". Below is a short example.

a<-c("Bill", "Jo", "Sue")
b<-c(3,4,10)
d<-c("Red", "Blue", "Yellow")
df<-data.frame(b,d,row.names=a)
colnames(df)<-c("age","favorite_color")
df
         age favorite_color
    Bill   3            Red
    Jo     4           Blue
    Sue   10         Yellow
str<-"car"
df$str<-character(nrow(df))
df
         age favorite_color  str
    Bill   3            Red      
    Jo     4           Blue      
    Sue   10         Yellow      

Is there a way to evaluate str while creating the new data frame column such that the column name is "car".

irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60
  • 5
    `df[[str]] <- `. – nrussell Jan 10 '17 at 13:11
  • 1
    @irritable_phd_syndrom You're right, that's hard to type your exact question title in google to find the answer... (no vote from my part, but really, try harder next time and don't whine being downvoted when your exact question title can be used as search keywords to find the answer). – Tensibai Jan 10 '17 at 13:30

1 Answers1

0

Your method tries to create a new column with the name "str", not the name that object str points to. Try this:

> df[,str]<-character(nrow(df))
> df
     age favorite_color car
Bill   3            Red
Jo     4           Blue
Sue   10         Yellow
Serhat Cevikel
  • 720
  • 3
  • 11