r - 在 R dataframe中,求和频率和联接标签

  显示原文与译文双语对照的内容
0 0

我有一张这样的桌子:

 Var1 Freq
1 6 1
2 7 4
3 8 1
4 10 2
5 11 6
6 12 1
7 13 2
8 15 1

我想用其他方式生成"纸盒",换句话说,和有变量 5 -9,10,15,0 - 。 这样,这种方式得到了:

 Var1 Freq
1 5-9 6
2 10-14 11
3 15-19. . .

不可能这么做。

时间:原作者:1个回答

0 0

尝试 cut

dat <- structure(list(Var1 = c(6L, 7L, 8L, 10L, 11L, 12L, 13L, 15L), 
Freq = c(1L, 4L, 1L, 2L, 6L, 1L, 2L, 1L)),. Names = c("Var1", 
"Freq"), class ="data.frame", row.names = c("1","2","3","4", 
"5","6","7","8"))
with(dat, aggregate(Freq, 
 list(Var1=cut(Var1, breaks=c(4,9,14,19),labels=c('5-9', '10-14', '15-19'))),
 FUN=sum))
# Var1 x
# 1 5-9 6
# 2 10-14 11
# 3 15-19 1

更新

如果有许多中断:

res1 <- with(dat, aggregate(Freq, list(Var1=cut(Var1, breaks=seq(4,19, by=5))),FUN=sum))

创建标签:

library(stringr)
indx1 <- scan(text=str_trim(gsub("[[:punct:]]+","",res1$Var1)),sep="")
transform(res1,Var1=apply(rbind(indx1[c(T,F)]+1,indx1[c(F,T)]),2,paste,collapse="-"))
# Var1 x
#1 5-9 6
#2 10-14 11
#3 15-19 1
原作者:
...