nisiois
nisiois

Reputation: 23

Merge single column dataframes in R

I'm trying to merge two data frames using the following code:

x<-data.frame(c(1:5))
colnames(x)[1]<- c("list1")

y<- data.frame(c(1:4))
colnames(y)[1]<-c("list2")

merge(x,y, by.x="list1", by.y="list2", all.x=T)

My ideal output is having a list like:

list1    list2
1        1 
2        2 
3        3
4        4
5        NA

However when I run the script above it will just give me this output:

list1
1     
2     
3     
4     
5

When I don't specify to keep all.x in the merge function the list looks similar as well. I'm not sure what exactly I'm doing wrong, as R isn't giving me any error messages and runs the code. I just want to get two single column lists and align them together like a VLOOKUP function.

Thank you!

Upvotes: 2

Views: 84

Answers (1)

akrun
akrun

Reputation: 887901

We can merge by 'row.names'

merge(x,y, by ='row.names', all=TRUE)[-1]
#     list1 list2
#1     1     1
#2     2     2
#3     3     3
#4     4     4
#5     5    NA

Or use match

transform(x, list2=y$list2[match(x$list1, y$list2)])

Upvotes: 2

Related Questions