我将此数据集保存为名为s2的矩阵
[,1]
0 4
0.5 1
1 6
10 61
15 28
2 8
20 25
23 1
25 4
3 3
30 44
我想通过它们的行名对它们进行分组,例如
[,1]
0-10 22
10-20 89
20-30 30
30-40 48
我想知道是否有比s[1,]=s[1,]+s2[2,]+..
更快的方式(因为我的数据集比这大得多),然后删除所有行?
我尝试使用aggregate
,但我读到一些有关wordStem()
的信息,但我什么都没找到。
谢谢
答案 0 :(得分:1)
假设矩阵为m
,您可以这样做:
library(tidyverse)
# specify your breaks for the grouping
brks = c(0,10,20,30,40)
data.frame(m) %>% # create a dataframe from your matrix
rownames_to_column() %>% # add rownames as a column
mutate(rowname = as.numeric(rowname)) %>% # make that column numeric (in order to group)
group_by(group = cut(rowname, breaks = brks, right = F)) %>% # use your breaks to group
summarise(m = sum(m)) %>% # get the sum of values for each group
data.frame() %>% # create a dataframe from tibble (in order to have rownames)
column_to_rownames("group") # add rownames from your group column
# m
# [0,10) 22
# [10,20) 89
# [20,30) 30
# [30,40) 44