Head and toes
Head and toes

Reputation: 659

Using paste in R

I have a question regarding the use of paste in R

a<-c(1,2,3,5,5,6,7,8)
b<-c(2,3,5,6,2,3,6,7)
d<-c(2,8,4,6,3,7,3,5)

df<-data.frame(a,b)
cbind(df,sugar=d)

Using the above code, I got this:

>  a b sugar
 1 1 2     2
 2 2 3     8
 3 3 5     4
 4 5 6     6
 5 5 2     3
 6 6 3     7
 7 7 6     3
 8 8 7     5

However, I wonder why I couldn't get the same results using paste function:

name<-c("sugar","salt","fat")
cbind(df,paste(name[1])=d)

Any help would be much appreciated!!

Upvotes: 2

Views: 515

Answers (2)

akrun
akrun

Reputation: 887118

If you need to create a new column with name stored in an object, try

 df[name[1]] <- d
 df
 #  a b sugar
 #1 1 2     2
 #2 2 3     8
 #3 3 5     4
 #4 5 6     6
 #5 5 2     3
 #6 6 3     7
 #7 7 6     3
 #8 8 7     5

Another option might be to use assign

 assign('df', `[[<-`(df, name[1], value=d))

Upvotes: 2

Robert Krzyzanowski
Robert Krzyzanowski

Reputation: 9344

You want to change the name, so try setNames.

 > setNames(cbind(df, d), c(colnames(df),name[1]))
   a b sugar
 1 1 2     2
 2 2 3     8
 3 3 5     4
 4 5 6     6
 5 5 2     3
 6 6 3     7
 7 7 6     3
 8 8 7     5

Upvotes: 0

Related Questions