Reputation: 169
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
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