【问题标题】:Increasing Multiplier增加乘数
【发布时间】:2018-07-08 17:56:35
【问题描述】:

我有一个数据框 (df),其中包含如下所示的两个变量:

   pricePerBusiness num_businesses
1           4228.966         3755
2           4966.552         3243
3           4678.073         3109
4           4752.259         2990
5           4545.194         2949 

我想创建一个新的数据框,它是该数据框和标量(在本例中为 15)的乘积,每行的值(1,2,3,...)都会增加,例如:

df2[1,] <- 1*df[1,]$pricePerBusiness + 0.15*df[1,]$num_businesses - 15*1
df2[2,] <- 1*df[2,]$pricePerBusiness + 0.15*df[2,]$num_businesses - 15*2
df2[3,] <- 1*df[3,]$pricePerBusiness + 0.15*df[3,]$num_businesses - 15*3

等等。但是我的数据框 (df) 有很多行,有没有更快的方法来做到这一点?

【问题讨论】:

  • 您能提供 MWE 吗?否则,我建议 mutate_all 来自 dplyr

标签: r loops dataframe multiplication scalar


【解决方案1】:

修改你的标量
as.numeric(rownames(df))*0.15

【讨论】:

    【解决方案2】:

    下面是一个可能的dplyr 解决方案。请确保您的问题是可重复的。

    # importing dplyr
    library(dplyr)
    
    # reproducing your original data frame
    df <- data_frame(
      pricePerBusiness = c(4228.966, 4966.552, 4678.073, 4752.259, 4545.194),
      num_businesses = c(3755, 3243, 3109, 2990, 2949)
    )
    
    # creating the final data frame you want
    df2 <- df %>%
      mutate(
        # constructing the term to substract
        penalty = 15 * 1:nrow(df),
        # computing the value needed
        value = pricePerBusiness + (0.15 * num_businesses) - penalty
      )
    

    【讨论】:

    • 谢谢您 - 我明白您现在所说的可重现是什么意思,并且将来会采用它。
    • 这个解决方案比单独计算每一列效率更高。在此类数据处理问题中,您可能希望从 dplyrdata.table 的强大功能中受益。
    【解决方案3】:

    另外,在 base 中使用 with():

    with(df,
      df2 <<- data.frame(result = pricePerBusiness + 0.15 * num_businesses - 15 *
                                  (1:length(num_businesses)))
    )
    

    【讨论】:

      【解决方案4】:

      我对 df 了解不多,但我搜索并找到了此链接,希望对您有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-26
        • 2018-05-09
        • 1970-01-01
        • 2018-06-26
        • 2014-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多