user124123
user124123

Reputation: 1683

Add columns to a dataframe based on entries from a character vector

I have a vector of character values which I wish to use in order to add columns to an existing dataframe, the columns named after the entries in the vector.

So if my vector were

vec
[1] "0.4" "0.5" "0.7" 

And my dataframe were

df
          chars     nums
1           a       1
2           b       2

I would like to produce:

df
          chars     nums    0.4      0.5    0.7
1           a       1      "0.4"    "0.5"  "0.7"
2           b       2      "0.4"    "0.5"  "0.7"

Does anyone know how I might do this without a for loop ?

Upvotes: 1

Views: 203

Answers (1)

akrun
akrun

Reputation: 887098

You can try

cbind(df,as.list(vec))

Or

df[vec] <- as.list(vec)
df
#  chars nums 0.4 0.5 0.7
#1     a    1 0.4 0.5 0.7
#2     b    2 0.4 0.5 0.7

Upvotes: 4

Related Questions