【发布时间】:2019-05-08 00:05:08
【问题描述】:
我有一个由昆虫现场采样数据的 420 行和 37 列组成的数据框。我试图对每 5 行的列值求和,以便每 5 行变为 1。此外,我试图使我的数据框($site,$date,$plot)中的非数值“折叠”,以便它们适合由我提到的总和组成的一个新行。
我已尝试使用此线程的建议:
Summing columns on every nth row of a data frame in R
包括使用包 dplyr 的 summarize_each 函数以及作为 data.table 一部分的 gl 和 colSums。
我已经在我的整个数据框上尝试过这些
库(data.table) setDT(FinalData)[, as.list(colSums(.SD)), by = gl(ceiling(420/5), 5, 420)]
这给了我:
colSums(.SD) 中的错误:“x”必须是数字
and
library(dplyr)
FinalData %>%
group_by(indx = gl(ceiling(420/5), 5, 420)) %>%
summarise_each(funs(sum))
which gives me error:
Error in Summary.factor(c(4L, 4L, 4L, 4L, 4L), na.rm = FALSE) :
‘sum’ not meaningful for factors
Site.Date.Plot CarA CarB CarC...
1.SL.VI.1 0 0 1
2.SL.VI.1 0 0 0
3.SL.VI.1 0 6 0
4.SL.VI.1 0 0 3
5.SL.VI.1 1 0 0
...
every 5 rows has a different $Site.Date.Plot. I expect this:
Site.Date.Plot CarA CarB CarC...
1. SL.VI.1 1 6 4
2. SL.VI.2 ... ... ...
But I get the above error messages from above.
【问题讨论】:
-
嗨,欢迎来到 SO!您能否提供一个数据样本,以便我们了解情况?看看how to make a reproducible example
-
嗨,Calum,我在帖子中提供了一小部分数据,我应该发布更多吗?你需要我的整个数据表吗?
-
最好使用
dput,以便人们可以复制和粘贴。此外,包括 20 行可能会更好,以验证每 5 行有一个不同的 Site.Date.Plot。所以,dput(FinalData[1:20, 1:4])会很棒。
标签: r data-manipulation