如何在R中执行二进制if语句?
我有一个数据集,其中有一列字母,后跟另一列1和0。我想为每封信合计“一”的数量,但不确定如何有效地做到这一点如何在R中执行二进制if语句?,r,R,我有一个数据集,其中有一列字母,后跟另一列1和0。我想为每封信合计“一”的数量,但不确定如何有效地做到这一点 我感谢你的帮助 我们可以按第一列('col1')分组,然后得到'col2'的sum library(dplyr) df1 %>% group_by(col1) %>% summarise(Total = sum(col2)) 或在数据表中 library(data.table) setDT(df1)[, .(Total = sum(col2)), col1]
我感谢你的帮助 我们可以按第一列('col1')分组,然后得到'col2'的
sum
library(dplyr)
df1 %>%
group_by(col1) %>%
summarise(Total = sum(col2))
或在
数据表中
library(data.table)
setDT(df1)[, .(Total = sum(col2)), col1]
或使用
base R
rowsum(df1$col2, df1$col1)
下面是一些其他基本的R解决方案
> tapply(df$col2, df$col1, sum)
a b c
1 1 2
> xtabs(col2~col1,df)
col1
a b c
1 1 2
虚拟数据
df <- structure(list(col1 = structure(c(1L, 3L, 1L, 2L, 1L, 3L, 3L,
2L, 2L, 3L), .Label = c("a", "b", "c"), class = "factor"), col2 = c(0,
0, 0, 0, 1, 1, 1, 1, 0, 0)), class = "data.frame", row.names = c(NA,
-10L))
> df
col1 col2
1 a 0
2 c 0
3 a 0
4 b 0
5 a 1
6 c 1
7 c 1
8 b 1
9 b 0
10 c 0
df
col1 col2
1 a 0
2c0
3 a 0
4B0
5 a 1
6 c 1
7 c 1
8 b 1
9B0
10c0
太棒了。非常感谢你。