Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge data frame and named vector

Tags:

merge

r

vector

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

like image 991
frank Avatar asked Aug 17 '18 13:08

frank


1 Answers

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]
like image 141
Ronak Shah Avatar answered Oct 21 '22 05:10

Ronak Shah