我在R中有一个数据帧,其中许多行是重复的:
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