frank
frank

Reputation: 3608

merge data frame and named 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

Upvotes: 11

Views: 5350

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388962

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]

Upvotes: 18

akrun
akrun

Reputation: 887078

We can create a column with the names of the vector and do the merge

merge(df, data.frame(v, col1 = names(v)), all.x = TRUE)
#   col1        col2  v
#1    a -1.61035092  2
#2    b -0.04848256  4
#3    c  2.74926847 56

In the OP's code, the row.names in the by.y should be in quotes

merge(df, data.frame(v), by.x = "col1", by.y = "row.names")
#  col1        col2  v
#1    a -1.61035092  2
#2    b -0.04848256  4
#3    c  2.74926847 56

Or use left_join from tidyverse

library(tidyverse)
left_join(df, data.frame(v, col1 = names(v)))

Upvotes: 10

Related Questions