【发布时间】:2019-01-24 01:09:08
【问题描述】:
我想对具有相同名称模式的列中的数据进行平均。如果您只有数字数据,其中一些示例非常有用:
How to calculate the mean of those columns in a data frame with the same column name
但是,我也有一列是一个因素。我可以删除此列然后 c(bind) 将其恢复,但这似乎很笨重。有没有办法可以使用 !is.factor(x) 之类的东西来忽略我的另一列?
df <-
as.data.frame(matrix(c(1,3,3,2,2,5,3,2,3,6,3,2,4,7,3,2,5,4,5,2,6,3,5,2),
ncol=6,
dimnames=list(NULL, c("A.1", "B.1", "C.1", "B.2", "A.2", "C.2"))))
char = c("Apple", "banana", "cat", "rainbow")
df = cbind(char, df)
res <- as.data.frame(sapply(unique(names(df)), function(col)
rowMeans(df[names(df) == col] )))
预期结果是:
res
char A B C
Apple 3.0 3 4.5
banana 3.5 6 4.5
cat 4.0 3 4.0
rainbow 2.0 2 2.0
错误是:
` Error in rowMeans(df[names(df) == col]) : 'x' must be numeric `
【问题讨论】:
-
您的错误是由于
char列是character向量而不是numeric向量。
标签: r