【问题标题】:How can I take the row product of columns in a dataframe with a common string如何使用公共字符串获取数据框中列的行积
【发布时间】:2019-05-09 15:26:27
【问题描述】:

我有 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,但这需要矩阵格式。

【问题讨论】:

  • 您是否尝试将as.matrix(df) 添加到您的rowProds 呼叫中,而不是直接使用df?
  • 这有很多骗子。请参阅 here 或 here 或 here 和许多其他人。

标签: r


【解决方案1】:

然后将其转换为矩阵格式并选择以"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)

【讨论】:

  • 谢谢!正是我需要的。
猜你喜欢
  • 2020-11-21
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 2017-01-25
  • 2021-05-19
  • 1970-01-01
相关资源
最近更新 更多