小编Mon*_*eck的帖子

根据R中的匹配条件组合行中的值

我有一个关于在R中聚合值的简单问题

假设我有一个数据帧:

DF <- data.frame(col1=c("Type 1", "Type 1B", "Type 2"), col2=c(1, 2, 3))  
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

     col1 col2
1  Type 1    1
2 Type 1B    2
3  Type 2    3
Run Code Online (Sandbox Code Playgroud)

我注意到,我有Type 1Type 1B数据,所以我想结合Type 1BType 1.

所以我决定使用dplyr:

filter(DF, col1=='Type 1' | col1=='Type 1B') %>%
  summarise(n = sum(col2))
Run Code Online (Sandbox Code Playgroud)

但现在我需要坚持下去:

DF2 <- data.frame('Type 1', filter(DF, col1=='Type 1' | col1=='Type 1B') %>%
  summarise(n = sum(col2)))
Run Code Online (Sandbox Code Playgroud)

我想我想把cbind这个新的DF2重新回到原来的DF,但这意味着我必须将列名设置为一致:

names(DF2) <- c('col1', 'col2')
Run Code Online (Sandbox Code Playgroud)

好的,现在我可以回复:

rbind(DF2, DF[3,])
Run Code Online (Sandbox Code Playgroud)

结果?有效.... …

r dataframe

8
推荐指数
2
解决办法
1923
查看次数

标签 统计

dataframe ×1

r ×1