I have a data frame and a name vector:
df=data.frame(col1=letters[1:3],col2=rnorm(3))
v=c(a=2,b=4,c=56,d=65)
I want to merge them, and keep only the values from the data frame
v=data.frame(v)
merge(df,v,by.x='col1',by.y=row.names,all.x=TRUE)
Error in as.vector(x, mode) :
cannot coerce type 'closure' to vector of type 'any'
I want:
col1 rnorm.3. v
1 a 0.6182781 2
2 b 0.9559001 4
3 c -0.5459661 56
Note my real data is 1M rows and 1.5M named vector
We can match
the col1
with names
of v
df$v <- v[match(df$col1, names(v))]
df
# col1 col2 v
#1 a 0.6658478 2
#2 b -1.6029447 4
#3 c 0.9019324 56
A more simple approach by @Frank in comments ,
df$v <- v[df$col1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With