使用 R 根据数据框中列中值的频率对数据进行分组
Group data according to frequency of values in a column in a data frame using R
我有一个如下所示的数据框:
a b
1 23
2 34
1 34
3 45
1 56
3 567
2 67
2 90
1 91
3 98
我想获取根据第一列中值的频率对行进行分组的数据框。输出应如下所示:
a b freq
1 23 4
1 34 4
1 56 4
1 91 4
2 34 3
2 67 3
2 90 3
3 45 3
3 567 3
3 98 3
我在R中写了如下代码:
import library(dplyr)
setDT(df)[,freq := .N, by = "a"]
sorted = df[order(freq, decreasing = T),]
sorted
但是,我得到以下数据框作为输出。
a b freq
1: 1 23 4
2: 1 34 4
3: 1 56 4
4: 1 91 4
5: 2 34 3
6: 3 45 3
7: 3 567 3
8: 2 67 3
9: 2 90 3
10: 3 98 3
我该如何解决这个问题?
我们可以使用n()
library(dplyr)
df1 %>%
group_by(a) %>%
mutate(freq = n()) %>%
arrange(a, desc(freq))
# A tibble: 10 x 3
# Groups: a [3]
# a b freq
# <int> <int> <int>
# 1 1 23 4
# 2 1 34 4
# 3 1 56 4
# 4 1 91 4
# 5 2 34 3
# 6 2 67 3
# 7 2 90 3
# 8 3 45 3
# 9 3 567 3
#10 3 98 3
您似乎想使用 data.table
包中的 setorder
。
您已按 freq
对数据进行排序,但您还想对列 a
应用排序。
setorder
示例:
> set.seed(12)
> df <- data.table(freq = sample(5, 5), a = sample(5, 5))
> df
freq a
1: 1 1
2: 4 5
3: 3 2
4: 5 4
5: 2 3
> setorder(df, freq, a)
> df
freq a
1: 1 1
2: 2 3
3: 3 2
4: 4 5
5: 5 4
> df <- read.table(text = 'a b
+ 1 23
+ 2 34
+ 1 34
+ 3 45
+ 1 56
+ 3 567
+ 2 67
+ 2 90
+ 1 91
+ 3 98', header = T, stringsAsFactors = F)
>
> df %>% group_by(a) %>%
+ mutate(Freq = n()) %>%
+ ungroup() %>%
+ arrange(a)
# A tibble: 10 × 3
a b Freq
<int> <int> <int>
1 1 23 4
2 1 34 4
3 1 56 4
4 1 91 4
5 2 34 3
6 2 67 3
7 2 90 3
8 3 45 3
9 3 567 3
10 3 98 3
我有一个如下所示的数据框:
a b
1 23
2 34
1 34
3 45
1 56
3 567
2 67
2 90
1 91
3 98
我想获取根据第一列中值的频率对行进行分组的数据框。输出应如下所示:
a b freq
1 23 4
1 34 4
1 56 4
1 91 4
2 34 3
2 67 3
2 90 3
3 45 3
3 567 3
3 98 3
我在R中写了如下代码:
import library(dplyr)
setDT(df)[,freq := .N, by = "a"]
sorted = df[order(freq, decreasing = T),]
sorted
但是,我得到以下数据框作为输出。
a b freq
1: 1 23 4
2: 1 34 4
3: 1 56 4
4: 1 91 4
5: 2 34 3
6: 3 45 3
7: 3 567 3
8: 2 67 3
9: 2 90 3
10: 3 98 3
我该如何解决这个问题?
我们可以使用n()
library(dplyr)
df1 %>%
group_by(a) %>%
mutate(freq = n()) %>%
arrange(a, desc(freq))
# A tibble: 10 x 3
# Groups: a [3]
# a b freq
# <int> <int> <int>
# 1 1 23 4
# 2 1 34 4
# 3 1 56 4
# 4 1 91 4
# 5 2 34 3
# 6 2 67 3
# 7 2 90 3
# 8 3 45 3
# 9 3 567 3
#10 3 98 3
您似乎想使用 data.table
包中的 setorder
。
您已按 freq
对数据进行排序,但您还想对列 a
应用排序。
setorder
示例:
> set.seed(12)
> df <- data.table(freq = sample(5, 5), a = sample(5, 5))
> df
freq a
1: 1 1
2: 4 5
3: 3 2
4: 5 4
5: 2 3
> setorder(df, freq, a)
> df
freq a
1: 1 1
2: 2 3
3: 3 2
4: 4 5
5: 5 4
> df <- read.table(text = 'a b
+ 1 23
+ 2 34
+ 1 34
+ 3 45
+ 1 56
+ 3 567
+ 2 67
+ 2 90
+ 1 91
+ 3 98', header = T, stringsAsFactors = F)
>
> df %>% group_by(a) %>%
+ mutate(Freq = n()) %>%
+ ungroup() %>%
+ arrange(a)
# A tibble: 10 × 3
a b Freq
<int> <int> <int>
1 1 23 4
2 1 34 4
3 1 56 4
4 1 91 4
5 2 34 3
6 2 67 3
7 2 90 3
8 3 45 3
9 3 567 3
10 3 98 3