R.3.3.2
想象一个载体
a <- c(3,2,5,6,7,8,2,9)
我想将a
归类为less or equal than 4
和greater than 4
。
当我使用table(a)
我需要获得如下结果:
less or equal than 4 greater than 4
3 5
如何获得此结果?有什么建议吗?提前谢谢。
答案 0 :(得分:2)
另一种选择是将cut
功能与table
结合使用:
table(cut(a, breaks = c(-Inf, 4, Inf),
labels = c('less and equal than 4','greater than 4'))
)
给出:
less and equal than 4 greater than 4
3 5
答案 1 :(得分:1)
为什么不使用
table(a>4)
答案 2 :(得分:0)
您可以找到哪个值属于哪个组,并计算该组中的值数。
a <- c(3,2,5,6,7,8,2,9)
x <- data.frame(a, test = a <= 4,
txt = ifelse(a <= 4, "less or equal to 4", "greater than 4"))
aggregate(a ~ test, data = x, length)
test a
1 FALSE 5
2 TRUE 3
aggregate(a ~ txt, data = x, FUN = length)
txt a
1 greater than 4 5
2 less or equal to 4 3
第三种选择。
table(x$txt)
greater than 4 less or equal to 4
5 3
答案 3 :(得分:0)
基于@Jaap答案,使用管道%>%
也许更好一些。
虚拟数据:
a <- c(3,2,5,6,7,8,2,9)
# combine functions using pipes %>%
a %>%
cut(breaks = c(-Inf, 4, Inf),
labels = c('less and equal than 4','greater than 4')) %>%
table
其中给出带有标签的结果:
less and equal than 4 greater than 4
3 5
如果您希望使用比例表,请在管道的末尾添加prop.table
:
a %>%
cut(breaks = c(-Inf, 4, Inf),
labels = c('less and equal than 4','greater than 4')) %>%
table %>%
prop.table # this was added
哪个给出结果:
less and equal than 4 greater than 4
0.375 0.625