【问题标题】:Recode multiple columns to create new columns of df重新编码多个列以创建 df 的新列
【发布时间】:2017-12-13 23:30:18
【问题描述】:

我正在尝试编写一个函数来改变df 中的多个列,并为每个重新编码的变量生成一个新列。在这种情况下,我正在运行的突变是从 15 中减去列中的每个元素。我能够为三列编写以下代码,这是可行的,但将来我想在 20 多列上运行类似的东西,并且写出每个新的列名(就像你在 mutate 中所做的那样)似乎很麻烦。
我似乎无法让lapply 使用重新编码或变异函数来生成新列。

df2 <- mutate(df1, new_col1 = 15-old_col1, 
         new_col2 = 15 - old_col2, new_col3 = 15 - old_col3)

【问题讨论】:

  • 你可以使用 mutate_all( ) 。

标签: r lapply recode dplyr


【解决方案1】:

data.table 解决方案,假设您想要改变所有列*(请参阅下面的更灵活的版本)。

*正如 @sb0709 在 cmets 中提到的那样,mutate_all 也会这样做。

library( data.table )
df <- data.table( old_col_1 = 20:24,
                  old_col_2 = 55:49,
              old_col_3 = rnorm( 5, 100, 30 ) )

df[ , sub( "old", "new", names( df ) ) := lapply( .SD, function(x) 15-x ) ]

这给出了:

R> df
    old_col_1 old_col_2 old_col_3 new_col_1 new_col_2  new_col_3
 1:        20        55  86.29104        -5       -40  -71.29104
 2:        21        56 144.21564        -6       -41 -129.21564
 3:        22        57 104.84574        -7       -42  -89.84574
 4:        23        58  93.18084        -8       -43  -78.18084
 5:        24        59 104.96188        -9       -44  -89.96188

如果您想选择少于所有列,您只需将names 向量和.SD 列表子集。例如,仅在第 2 列和第 3 列上运行您的突变:

df[ , sub( "old", "new", names( df )[2:3] ) := lapply( .SD[,2:3], function(x) 15-x ) ]

而是给出:

R> df
    old_col_1 old_col_2 old_col_3 new_col_2  new_col_3
 1:        20        55 138.28667       -40 -123.28667
 2:        21        56  69.03836       -41  -54.03836
 3:        22        57 147.39790       -42 -132.39790
 4:        23        58  88.15505       -43  -73.15505
 5:        24        59  28.96437       -44  -13.96437

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2018-05-11
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多