r语言 - 如何在数据集中添加出现次数的列?



我在R中有一个数据帧,其中许多行是重复的:

tbody> <<tr>橙色橙色蓝色橙色金枪鱼
header1 header2
金枪鱼苹果
鲑鱼
鳟鱼
鳟鱼
鲑鱼
苹果

最简单的是从dplyr直接使用count:

library(dplyr)
df %>% 
count(header1, header2)

header1 header2 n
1    blue   trout 1
2  orange  salmon 2
3  orange   trout 1
4    tuna   apple 2

或与tally:

df %>%
group_by(header1, header2) %>%
tally() %>% 
ungroup

data.table的另一个选项:

library(data.table)
dt <- as.data.table(df)
dt[, list(count =.N), by=list(header1, header2)]

或者你可以从plyr:

中使用ddply
plyr::ddply(df, c("header1", "header2"), nrow)

如果两列的顺序无关紧要,那么您可以这样做,我们首先将每一行拆分为列表中自己的数据框。然后,我们可以sort这两列,并为每一行折叠成一个字符串,然后我们可以使用table计算出现次数,然后转换回数据帧。

split(df2, seq(nrow(df2))) %>%
sapply(., function(x)
unlist(x) %>% sort() %>% paste(collapse = " ")) %>%
table(combo = .) %>%
data.frame

或者我们也可以利用purrr:

来使用tidyverse
library(tidyverse)
df2 %>% 
pmap_dfr(~list(...)[order(c(...))] %>% set_names(names(df2))) %>%
group_by_all %>% 
count

输出

combo Freq
1    apple tuna    3
2    blue trout    1
3 orange salmon    2
4  orange trout    1

数据

df2<- structure(list(header1 = c("tuna", "orange", "orange", "blue", 
"orange", "tuna", "apple"), header2 = c("apple", "salmon", "trout", 
"trout", "salmon", "apple", "tuna")), class = "data.frame", row.names = c(NA, 
-7L))
#  header1 header2
#1    tuna   apple
#2  orange  salmon
#3  orange   trout
#4    blue   trout
#5  orange  salmon
#6    tuna   apple
#7   apple    tuna

一个可能的解决方案:

library(dplyr)
df %>% 
group_by(header1, header2) %>% 
summarise(n = n(), .groups = "drop")
#> # A tibble: 4 × 3
#>   header1 header2     n
#>   <chr>   <chr>   <int>
#> 1 blue    trout       1
#> 2 orange  salmon      2
#> 3 orange  trout       1
#> 4 tuna    apple       2

最新更新