Dougie Hwang
Dougie Hwang

Reputation: 113

How can I join two data that have different types of data?

Let's say I have two data. one is like this:

names |height
------|------
"ab"  |176
------|--------
"aa"  |168
------|--------
"ac"  |189
------|--------
"ad"  |179

and the other is like this:

names           weight
c("aa","ab")    58
c("ac","ae")    70
"ad"            68

so the second names are list, but the first names are just vector. I want to make like this:

names  height  weight
"ab"   176     58
"aa"   168     58
"ac"   189     70
"ad"   179     68

I tried to use left_join, but it didn't work. And I also tried to make list to vector. When I made list to vector, the problem is lengths are different each other. Please, can you help me??? This is my first question on stackoverflow.

Add my code

names<-c("ab","aa","ac","ad")
height<-c(176,168,189,179)
data1<-cbind(names,height)
names<-list(c("aa","ab"),c("ac","ae"),"ad")
weight<-c(58,70,68)
data2<-cbind(names,weight)
data1<-as.data.frame(data1) ;data1;str(data1)
data2<-as.data.frame(data2) ;data2;str(data2)
data2 %>%

unnest %>% left_join(.,data1, by = "names")

Upvotes: 2

Views: 1722

Answers (1)

akrun
akrun

Reputation: 886978

We can use tidyverse assuming that the 'names' column is a list in the second dataset. With unnest, convert it to a vector and then left_join with the first dataset by 'names'

library(tidyverse)
df2 %>%
   unnest %>%
   left_join(df1, ., by = "names") 
#   names height weight
#1    ab    176     58
#2    aa    168     58
#3    ac    189     70
#4    ad    179     68

data

df1 <- data.frame(names = c("ab", "aa", "ac", "ad"),
  height = c(176, 168, 189, 179), stringsAsFactors = FALSE)

df2 <- data.frame(names = I(list(c("aa", "ab"), c("ac", "ae"), "ad")),
  weight = c(58, 70, 68))

Upvotes: 2

Related Questions