在中为R中的频率表创建间隔
我在表单中创建了一个数据帧在中为R中的频率表创建间隔,r,dplyr,R,Dplyr,我在表单中创建了一个数据帧 FREQ CNT 0 5 1 20 2 1000 3 3 4 3 I want to further group my results to be in the following form: CUT CNT 0+1 25 2+3 1003 4+5 ... ..... 我曾尝试在dplyr中使用between和cut函数,
FREQ CNT
0 5
1 20
2 1000
3 3
4 3
I want to further group my results to be in the following form:
CUT CNT
0+1 25
2+3 1003
4+5 ...
.....
我曾尝试在dplyr中使用between和cut函数,但它只是在我的数据帧中添加了一个新的interval列。有人能给我一个很好的指示,说明如何实现这一点吗?一个使用
dplyr
的非优雅解决方案。。。可能是更好的方法
dat <- data.frame(FREQ = c(0,1,2,3,4), CNT = c(5,20,1000, 3, 3))
dat2 <- dat %>%
mutate(index = 0:(nrow(dat)-1)%/%2) %>%
group_by(index)
dat2 %>%
summarise(new_CNT = sum(CNT)) %>%
left_join(dat2 %>%
mutate(CUT = paste0(FREQ[1], "+", FREQ[2])) %>%
distinct(index, CUT),
by = "index") %>%
select(-index)
# A tibble: 3 x 2
new_CNT CUT
<dbl> <chr>
1 25 0+1
2 1003 2+3
3 3 4+NA
dat%
分组依据(索引)
dat2%>%
总结(新碳纳米管=总和(碳纳米管))%>%
左联合(dat2%>%
突变(剪切=粘贴0(频率[1],“+”,频率[2]))%>%
不同的(索引、切割),
by=“index”)%>%
选择(-index)
#一个tibble:3x2
新切口
1 25 0+1
2 1003 2+3
34+NA
在dplyr
中有一种方法:
library(dplyr)
df <- df %>%
mutate(id = 1:n()) %>%
mutate(new_freq = ifelse(id %% 2 != 0, paste0(FREQ, "+", lead(FREQ, 1)), paste0(lag(FREQ, 1), "+", FREQ)))
df <- df %>%
group_by(new_freq) %>%
mutate(new_cnt = sum(CNT))
unique(df[, 4:5])
# A tibble: 2 x 2
# Groups: new_freq [2]
# new_freq new_cnt
# <chr> <int>
#1 0+1 25
#2 2+3 1003
库(dplyr)
df%
变异(id=1:n())%>%
变异(新频率=ifelse(id%%2!=0,粘贴0(频率,“+”,前置(频率,1)),粘贴0(滞后(频率,1),“+”,频率)))
df%
分组依据(新频率)%>%
变异(new_cnt=sum(cnt))
唯一(df[,4:5])
#一个tibble:2x2
#组别:新频率[2]
#新建频率新建
#
#1 0+1 25
#2 2+3 1003
数据
df谢谢你的帮助,如果我想分组说10秒和20秒而不是2秒,我该如何修改它呢谢谢你看到两种方法很有帮助
df <- structure(list(FREQ = 0:3, CNT = c(5L, 20L, 1000L, 3L)), class = "data.frame", row.names = c(NA, -4L))