【问题标题】:How to perform function on certain columns and then perform another function on that如何在某些列上执行功能,然后在该列上执行另一个功能
【发布时间】:2021-09-06 11:33:33
【问题描述】:

假设我有这些数据:

a <- data.frame(group=c("one", "two", "three"), a = c(1,2,3), b=c(4,3,5), c=c(8,2,1))

  group a b c
1   one 1 4 8
2   two 2 3 2
3 three 3 5 1

我想对第 2-4 列执行一个函数,然后对这些结果执行另一个函数。特别是,我想对这些列中的每一列进行平方,然后将结果相加。

这是我想要得到的:

  group a b c want
1   one 1 4 8   81
2   two 2 3 2   17
3 three 3 5 1   35

(对于第一行,811^2 + 4^2 + 8^2获取。

我感觉这可能涉及lapply 之类的东西,但我不确定。

请注意,我想使用其他东西而不是类似的东西来做到这一点

a %>% mutate(want = a^2 + b^2 + c^2)

(原则上可能需要考虑数千列)。

base R 和 tidyverse 中的解决方案值得赞赏。

【问题讨论】:

    标签: r function tidyverse


    【解决方案1】:

    我们可以select 列,获取功率,reduce 返回总和

    library(dplyr)
    library(purrr)
    a %>%
         mutate(want = select(cur_data(), -group)^2 %>% 
                      reduce(`+`))
    

    -输出

      group a b c want
    1   one 1 4 8   81
    2   two 2 3 2   17
    3 three 3 5 1   35
    

    或使用rowSums

    a %>% 
        mutate(want = rowSums(select(cur_data(), -group)^2, na.rm = TRUE))
    

    -输出

       group a b c want
    1   one 1 4 8   81
    2   two 2 3 2   17
    3 three 3 5 1   35
    

    或者如果使用的函数不是^,也可以循环across列然后用reduce添加(+)或使用rowSums

    a %>% 
        mutate(want = rowSums(across(-group, ~ .^2)))
      group a b c want
    1   one 1 4 8   81
    2   two 2 3 2   17
    3 three 3 5 1   35
    

    【讨论】:

      【解决方案2】:

      基本 R 选项

      a$want <- rowSums(a[-1]^2)
      

      给予

      > a
        group a b c want
      1   one 1 4 8   81
      2   two 2 3 2   17
      3 three 3 5 1   35
      

      【讨论】:

        猜你喜欢
        • 2010-10-12
        • 1970-01-01
        • 2015-10-19
        • 1970-01-01
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-16
        相关资源
        最近更新 更多