【问题标题】:Adding different numbers to different columns of a dataframe向数据框的不同列添加不同的数字
【发布时间】:2021-06-06 20:52:27
【问题描述】:

假设我正在使用 mtcars 数据集,我想添加:
1 到列中的所有值:mpg
2 到列中的所有值:cyl
3 到列中的所有值:disp
我想将所有列保留在 mtcars 中,并通过它们的名称而不是它们的索引来引用这些列。

这是我目前的尝试:

library("tidyverse")
library("rlang")
data(mtcars)

mtcars_colnames <- quo(c("mpg", "cyl", "disp"))
num <- c(1, 2, 3)

mtcars %>% mutate(across(!!! mtcars_colnames, function(x) {x + num[col(.)]}))

我不知道如何将 (1,2,3) 动态添加到列 (mpg, cyl, disp)。 提前致谢。

【问题讨论】:

    标签: r dplyr tidyverse rlang


    【解决方案1】:

    我们可以通过只传递一个字符串向量而不是quosures 和一个命名向量来更改输入,然后使用across 中的cur_column 来匹配命名向量'num ',得到对应的值并做加法

    library(dplyr)
    mtcars_colnames <- c("mpg", "cyl", "disp")
    num <- setNames(c(1, 2, 3), mtcars_colnames)
    mtcars1 <- mtcars %>%
        mutate(across(all_of(mtcars_colnames), ~ num[cur_column()] + .))
    

    -检查输出

    # // old data
    mtcars %>% 
        select(all_of(mtcars_colnames)) %>% 
        slice_head(n = 5)
    #                   mpg cyl disp
    #Mazda RX4         21.0   6  160
    #Mazda RX4 Wag     21.0   6  160
    #Datsun 710        22.8   4  108
    #Hornet 4 Drive    21.4   6  258
    #Hornet Sportabout 18.7   8  360
    
    # // new data
    mtcars1 %>% 
        select(all_of(mtcars_colnames)) %>%
        slice_head(n = 5)
    #                   mpg cyl disp
    #Mazda RX4         22.0   8  163
    #Mazda RX4 Wag     22.0   8  163
    #Datsun 710        23.8   6  111
    #Hornet 4 Drive    22.4   8  261
    #Hornet Sportabout 19.7  10  363
    

    或者,如果我们更喜欢传递一个未命名的“num”向量,那么 match 和带有“mtcars_colnamesinside theacross”的cur_column 以返回索引,然后使用它来子集“num”

    mtcars1 <- mtcars %>%
        mutate(across(all_of(mtcars_colnames), 
               ~ num[match(cur_column(), mtcars_colnames)] + .))
    

    【讨论】:

      【解决方案2】:

      这里有 3 种基本 R 方法:

      mtcars_colnames <- c("mpg", "cyl", "disp")
      num <- c(1, 2, 3)
      df <- mtcars
      
      #option 1
      df[mtcars_colnames] <- sweep(df[mtcars_colnames], 2, num, `+`)
      #option 2
      df[mtcars_colnames] <- Map(`+`, df[mtcars_colnames], num)
      #option 3
      df[mtcars_colnames] <- t(t(df[mtcars_colnames]) + num)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-07-05
        • 2023-03-23
        • 2017-04-26
        • 1970-01-01
        相关资源
        最近更新 更多