【发布时间】:2019-07-13 15:35:21
【问题描述】:
我正在尝试取消嵌套每个单元格的值并不总是相同数量的两列,然后连接在两列之间具有对应关系的值。例如:
library('dplyr')
library('tidyr')
#Sample Data
df <- data.frame(id = c(1:4),
first.names = c('Michael, Jim', 'Michael, Michael', 'Creed', 'Creed, Jim'),
last.names = c('Scott, Halpert', 'Scott, Cera', '', 'Halpert'))
并非 df$first.names 中的所有值都与 df$last.names 中的值相关联。我试图得到以下结果:
#Desired output
df.results <- data.frame(id = c(1,1,2,2,3,4,4),
first.names = c('Michael', 'Jim', 'Michael', 'Michael', 'Creed', 'Creed', 'Jim'),
last.names = c('Scott', 'Halpert', 'Scott', 'Cera', '', '', 'Halpert'),
full.names = c('Michael Scott', 'Jim Halpert', 'Michael Scott', 'Michael Cera', 'Creed', 'Creed', 'Jim Halpert'))
我尝试过使用 unnest,它适用于 first.names,但不适用于 last.names(它会删除 last.names 为空白的行):
#convert to characters
df$first.names <- as.character(df$first.names)
df$last.names <- as.character(df$last.names)
#Unnest first names
df <- df %>%
transform(first.names = strsplit(first.names, ',')) %>%
unnest(first.names)%>%
transform(last.names = strsplit(last.names, ',')) %>%
unnest(last.names)
然后我打算删除重复的行,但这仍然不能解决 df$first.names 中的值在 df$last.names 中没有值的问题
有没有更好的方法来做到这一点?
【问题讨论】:
-
数据中的一个问题是最后一行“last.names”只有一个条目。你如何决定它应该与'first.names'中的'Creed'或'Jim'一起使用。这是基于“吉姆”的早期条目。但是当有人姓氏相同时,这可能会导致问题
-
这是我面临的一个问题,目前,我知道只有某些名字没有姓氏。我在想也许字典会有所帮助,但这更多是我的 python 背景......我正在尝试运行你的代码,安装 tidyverse 包时遇到问题
标签: r concatenation