如何合并数据框中的行并组合单元格中的因子值
How to merge rows in a dataframe and combine factor-values in cells
我在 R 中有一个数据框,我想在其中合并某些行并组合这些行中某些单元格的值。想象一下以下数据框:
Col.1<-c("a","b","b","a","c","c","c","d")
Col.2<-c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
df<-data.frame(Col.1, Col.2)
df
Col.1 Col.2
a mouse
b cat
b dog
a bird
c giraffe
c elephant
c zebra
d worm
我想合并 Col.1 中的值相同的所有相邻行,并相应地合并 Col.2 中的值。
最终结果应该是这样的:
Col.1 Col.2
a mouse
b cat dog
a bird
c giraffe elephant zebra
d worm
我曾尝试使用 dplyr 解决方案(如:ddply(df, .(Col.1), summarize, Col.2 = sum(Col.2))
),但求和命令不适用于因子值。
我们可以通过粘贴进行分组。要对相邻的相似元素进行分组,可以使用 data.table
中的 rleid
,然后 summarise
'Col.2' 的值 paste
ing
library(dplyr)
library(data.table)
library(stringr)
df %>%
group_by(Col.1, grp = rleid(Col.1)) %>%
summarise(Col.2 = str_c(Col.2, collapse=' ')) %>%
ungroup %>%
select(-grp)
# A tibble: 5 x 2
# Col.1 Col.2
# <fct> <chr>
#1 a mouse
#2 a bird
#3 b cat dog
#4 c giraffe elephant zebra
#5 d worm
注意:这与 OP post
中显示的输出相匹配
编辑:错过了 "adjacent" 位。请参阅下面来自 .
的使用基函数 rle
的解决方案
Col.1 <- c("a","b","b","a","c","c","c","d")
Col.2 <- c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
df <- tibble(Col.1, Col.2)
rlel <- rle(df$Col.1)$length
df %>%
mutate(adj = unlist(lapply(1:length(rlel), function(i) rep(i, rlel[i])))) %>%
group_by(Col.1, adj) %>%
summarize(New.Col.2 = paste(Col.2, collapse = " ")) %>%
ungroup %>% arrange(adj) %>% select(-adj)
# A tibble: 5 x 2
Col.1 New.Col.2
<chr> <chr>
1 a mouse
2 b cat dog
3 a bird
4 c giraffe elephant zebra
5 d worm
我在 R 中有一个数据框,我想在其中合并某些行并组合这些行中某些单元格的值。想象一下以下数据框:
Col.1<-c("a","b","b","a","c","c","c","d")
Col.2<-c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
df<-data.frame(Col.1, Col.2)
df
Col.1 Col.2
a mouse
b cat
b dog
a bird
c giraffe
c elephant
c zebra
d worm
我想合并 Col.1 中的值相同的所有相邻行,并相应地合并 Col.2 中的值。
最终结果应该是这样的:
Col.1 Col.2
a mouse
b cat dog
a bird
c giraffe elephant zebra
d worm
我曾尝试使用 dplyr 解决方案(如:ddply(df, .(Col.1), summarize, Col.2 = sum(Col.2))
),但求和命令不适用于因子值。
我们可以通过粘贴进行分组。要对相邻的相似元素进行分组,可以使用 data.table
中的 rleid
,然后 summarise
'Col.2' 的值 paste
ing
library(dplyr)
library(data.table)
library(stringr)
df %>%
group_by(Col.1, grp = rleid(Col.1)) %>%
summarise(Col.2 = str_c(Col.2, collapse=' ')) %>%
ungroup %>%
select(-grp)
# A tibble: 5 x 2
# Col.1 Col.2
# <fct> <chr>
#1 a mouse
#2 a bird
#3 b cat dog
#4 c giraffe elephant zebra
#5 d worm
注意:这与 OP post
中显示的输出相匹配编辑:错过了 "adjacent" 位。请参阅下面来自
rle
的解决方案
Col.1 <- c("a","b","b","a","c","c","c","d")
Col.2 <- c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
df <- tibble(Col.1, Col.2)
rlel <- rle(df$Col.1)$length
df %>%
mutate(adj = unlist(lapply(1:length(rlel), function(i) rep(i, rlel[i])))) %>%
group_by(Col.1, adj) %>%
summarize(New.Col.2 = paste(Col.2, collapse = " ")) %>%
ungroup %>% arrange(adj) %>% select(-adj)
# A tibble: 5 x 2
Col.1 New.Col.2
<chr> <chr>
1 a mouse
2 b cat dog
3 a bird
4 c giraffe elephant zebra
5 d worm