我生成了以下数据框:
random <- data.frame(replicate(10, sample(1:12, 564, replace=TRUE)))
它包含10列和564行。列中的每个数字都代表一天(1-12)。我向此数据框添加了一个新列,其中没有特殊顺序包含单词“ Green”,“ Pink”和“ Red”,并使用我拥有的现有数据填充所有564行:
random <- fruit$color
这是我想做的:
对于第1-10列,创建以下计数表:
Day Green Pink Red
1 # # #
2 # # #
3 # # #
4 # # #
... # # #
12 # # #
因此,例如,我应该能够从该表中知道第1列中第1天果岭的数量。重要的是,不同列的颜色计数必须彼此区分。
而且有一个有趣的转折!
需要为每种颜色添加第9天和第10天的计数,因此每个表格应如下所示:
Day Green Pink Red
1 # # #
2 # # #
3 # # #
4 # # #
5 # # #
6 # # #
7 # # #
8 # # #
9 - 10 # # #
11 # # #
12 # # #
到目前为止,我已经尝试使用ddply进行强制转换并遍历每一列,但是我对循环并不熟悉。这是到目前为止我得到的博洛尼亚:
for(i in names(random)) {
random_counts <- ddply(random, c('color', i), function(x) c(count=nrow(x)))
random_counts <- cast(random_counts, i ~ color, mean, value='count')
random_counts
}
帮助将不胜感激!谢谢
这是一个base
替代方案:
# slightly smaller toy data
random <- data.frame(replicate(2, sample(1:5, 20, replace = TRUE)))
color <- sample(c("Green", "Pink", "Red"), nrow(random), replace = TRUE)
# use cut to put e.g. 3 and 4 in the same interval
random[] <- lapply(random, function(x) cut(x, breaks = c(0, 1, 2, 4, 5)))
# count
lapply(random, function(x) table(x, color))
# $X1
# color
# x Green Pink Red
# (0,1] 2 0 1
# (1,2] 3 0 2
# (2,4] 3 4 2
# (4,5] 1 1 1
#
# $X2
# color
# x Green Pink Red
# (0,1] 3 0 1
# (1,2] 4 0 1
# (2,4] 1 3 1
# (4,5] 1 2 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句