Björn Butter
Björn Butter

Reputation: 169

assign values to named dataframe columns from named vector

Lets suppose I have a vector and a dataframe:

v <- c(2,2,4,5,6)
names(v) <- c("F", "J", "D", "A", "B")

df<- setNames(data.frame(matrix(ncol = 10, nrow = 1)), c("A" ,"B", "C", "D", "E", "F", "G", "H", "I", "J"))

I now want to assign values stored in v to the matching column of df. A "match" would be indicated, that names of v and columnnames of 'df' are indentical.

Thanks for the help!

Upvotes: 0

Views: 606

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388862

We can directly subset the columns from names and assign value

df[names(v)] <- v
df
#  A B  C D  E F  G  H  I J
#1 5 6 NA 4 NA 2 NA NA NA 2

Upvotes: 1

Clemsang
Clemsang

Reputation: 5481

You can use match:

df[match(names(v), names(df))] <- v

Upvotes: 1

Related Questions