假设我有两个数据。 一个是这样的:
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 %>%
取消嵌套%>% left_join(.,data1, by = "姓名")
最佳答案
我们可以使用 tidyverse
假设“names”列是第二个数据集中的列表
。使用unnest
,将其转换为向量
,然后使用第一个数据集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
数据
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))
关于r - 如何连接两个具有不同类型数据的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45994395/