如何连接具有不同类型数据的两个数据?

时间:2017-09-01 06:28:15

标签: r left-join

假设我有两个数据。 一个是这样的:

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

另一个是这样的:

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

所以第二个名字是列表,但名字只是矢量。 我想这样做:

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

我尝试使用left_join,但它没有用。 而且我也尝试将列表设为矢量。 当我向矢量列表时,问题是长度彼此不同。 拜托,你能帮我吗? 这是我关于stackoverflow的第一个问题。

添加我的代码

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 %>%

不确定%&gt;%   left_join(。,data1,by =“names”)

1 个答案:

答案 0 :(得分:2)

我们可以使用tidyverse,假设第二个数据集中的“名称”列是list。使用unnest,将其转换为vector,然后将left_join转换为第一个数据集by'名称'

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

数据

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))