R按因子或整数列出数据框中的前n个条目
R list top n entries in a dataframe by factor or integer
我想为因子或整数的每个级别列出数据框中的前 n 个条目。这是我的代码:
index <- c(1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3)
prob <- runif(20,0,1)
x.df <- data.frame(cbind(index,prob))
x.df <- x.df[order(x.df$index,-x.df$prob),]
head(x.df[x.df$index==1,],n=3)
head(x.df[x.df$index==2,],n=3)
head(x.df[x.df$index==3,],n=3)
这样就可以了,但我不想为每个 level/integer 都明确地写一个 head 语句。谢谢
假设您的数据框按照您想要的方式排列,那么您可以这样做:
library(dplyr)
x.df %>%
group_by(index) %>% # for each index
slice(1:3) %>% # get top 3 rows
ungroup() # forget the grouping
# # A tibble: 9 x 2
# index prob
# <dbl> <dbl>
# 1 1 0.943
# 2 1 0.461
# 3 1 0.251
# 4 2 0.739
# 5 2 0.697
# 6 2 0.695
# 7 3 0.968
# 8 3 0.915
# 9 3 0.635
假设它是无序的
x.df %>%
group_by(index) %>%
top_n(3) %>%
ungroup()
在 base R 中,有一个名为 tapply
:
的分组方法
with(x.df, stack(tapply(prob, index, head, 3)))
# values ind
#1 0.9045300 1
#2 0.7651376 1
#3 0.3631891 1
#4 0.9471318 2
#5 0.9206743 2
#6 0.7675069 2
#7 0.9866379 3
#8 0.9149754 3
#9 0.7862320 3
还有 by
函数用于 data.frame
:
do.call(rbind, by(x.df, index, head, 3))
产生相同的结果
使用 data.table
包的简单解决方案-
> setDT(x.df)[,head(.SD,3),by=index]
输出-
index prob
1: 1 0.7863076
2: 1 0.7103228
3: 1 0.5657803
4: 2 0.9939695
5: 2 0.7517839
6: 2 0.7348664
7: 3 0.9260537
8: 3 0.5889305
9: 3 0.5557626
注意- 如果您的 prob
未订购,请使用此-
> setDT(x.df)[order(-prob),head(.SD,3),by=index]
我想为因子或整数的每个级别列出数据框中的前 n 个条目。这是我的代码:
index <- c(1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3)
prob <- runif(20,0,1)
x.df <- data.frame(cbind(index,prob))
x.df <- x.df[order(x.df$index,-x.df$prob),]
head(x.df[x.df$index==1,],n=3)
head(x.df[x.df$index==2,],n=3)
head(x.df[x.df$index==3,],n=3)
这样就可以了,但我不想为每个 level/integer 都明确地写一个 head 语句。谢谢
假设您的数据框按照您想要的方式排列,那么您可以这样做:
library(dplyr)
x.df %>%
group_by(index) %>% # for each index
slice(1:3) %>% # get top 3 rows
ungroup() # forget the grouping
# # A tibble: 9 x 2
# index prob
# <dbl> <dbl>
# 1 1 0.943
# 2 1 0.461
# 3 1 0.251
# 4 2 0.739
# 5 2 0.697
# 6 2 0.695
# 7 3 0.968
# 8 3 0.915
# 9 3 0.635
假设它是无序的
x.df %>%
group_by(index) %>%
top_n(3) %>%
ungroup()
在 base R 中,有一个名为 tapply
:
with(x.df, stack(tapply(prob, index, head, 3)))
# values ind
#1 0.9045300 1
#2 0.7651376 1
#3 0.3631891 1
#4 0.9471318 2
#5 0.9206743 2
#6 0.7675069 2
#7 0.9866379 3
#8 0.9149754 3
#9 0.7862320 3
还有 by
函数用于 data.frame
:
do.call(rbind, by(x.df, index, head, 3))
产生相同的结果
使用 data.table
包的简单解决方案-
> setDT(x.df)[,head(.SD,3),by=index]
输出-
index prob
1: 1 0.7863076
2: 1 0.7103228
3: 1 0.5657803
4: 2 0.9939695
5: 2 0.7517839
6: 2 0.7348664
7: 3 0.9260537
8: 3 0.5889305
9: 3 0.5557626
注意- 如果您的 prob
未订购,请使用此-
> setDT(x.df)[order(-prob),head(.SD,3),by=index]