我有 N 个以字符串“因子”开头的列。我想在数据框中创建一个额外的列来查找这些列的行积。
示例数据(我的实际数据集 N = 50):
df <- data.frame(Company = c("A","B","C","D","E"),
Factor1 = c(1,2,3,4,5),
Factor2 = c(5,4,3,2,1),
FactorN = c(2,4,6,8,10))
预期结果
df2 <- data.frame(Company = c("A","B","C","D","E"),
Factor1 = c(1,2,3,4,5),
Factor2 = c(5,4,3,2,1),
FactorN = c(2,4,6,8,10),
Factor_Product = c(10,32,54,64,50))
我已经尝试过 matrixStats 包中的 rowProds,但这需要矩阵格式。
然后将其转换为矩阵格式并选择以 "Factor"
matrixStats::rowProds(as.matrix(df[grep("^Factor", names(df))]))
#[1] 10 32 54 64 50
您也可以按apply
行使用
apply(df[grep("Factor", names(df))], 1, prod)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句