我正在尝试根据与列ID关联的中间值重新排序数据框。
我有一个包含ID列和2列值的数据框。
ID <- c("a","a","a","b","b","b","c","c","c","c")
alpha <- c(3,4,5,9,11,13,1,1,1,0)
beta <- c(2,3,4,3,4,5,4,5,6,7)
df <- data.frame(ID,alpha,beta)
ID alpha beta
1 a 3 2
2 a 4 3
3 a 5 4
4 b 9 3
5 b 11 4
6 b 13 5
7 c 1 4
8 c 1 5
9 c 1 6
10 c 0 7
我想重新排序此数据框,以便列ID基于alpha列中关联值的降序来处理:
ID alpha beta
1 b 9 3
2 b 11 4
3 b 13 5
4 a 3 2
5 a 4 3
6 a 5 4
7 c 1 4
8 c 1 5
9 c 1 6
10 c 0 7
这是不成功的:
df[reorder(df$ID, df$alpha, FUN = mean),]
答案 0 :(得分:0)
尝试
library(dplyr)
df %>% group_by(ID) %>% mutate(m = mean(alpha)) %>% arrange(desc(m)) %>% select(-m)
# A tibble: 10 x 3
# Groups: ID [3]
ID alpha beta
<fctr> <dbl> <dbl>
1 b 9 3
2 b 11 4
3 b 13 5
4 a 3 2
5 a 4 3
6 a 5 4
7 c 1 4
8 c 1 5
9 c 1 6
10 c 0 7
答案 1 :(得分:0)
以下是使用moviedata.array=vec_tfidf[m].toarray()[0]
data.table
或者,我们可以使用library(data.table)
setDT(df)[df[, mean(alpha), ID][order(-V1), .(ID)], on = .(ID)]
# ID alpha beta
#1: b 9 3
#2: b 11 4
#3: b 13 5
#4: a 3 2
#5: a 4 3
#6: a 5 4
#7: c 1 4
#8: c 1 5
#9: c 1 6
#10: c 0 7
中的ave
获取base R
,然后mean
order