【问题标题】:How to change the values of columns in a big dataframe using the names of variables?如何使用变量名称更改大数据框中列的值?
【发布时间】:2022-10-13 20:22:19
【问题描述】:

我有这个数据集(但我们假设它非常大,有很多行和列)

df = data.frame(x = c(1,0,0,1),
                y = c(0,0,1,1))

我希望每次都使用变量 x、y 等的名称,同时将 1 和 0 替换为是的如下 :

df = data.frame(x = c('yes_x','no_x','no_x','yes_x'),
                y = c('no_y','no_y','yes_y','yes_y'))

将不胜感激。谢谢

【问题讨论】:

    标签: r dataframe multiple-columns substitution


    【解决方案1】:

    dplyr,与cur_column

    library(dplyr)
    df %>% 
      mutate(across(x:y, 
                    ~ ifelse(.x == 1, "yes", "no") %>% 
                      paste(cur_column(), sep = "_")))
    

    输出

          x     y
    1 yes_x  no_y
    2  no_x  no_y
    3  no_x yes_y
    4 yes_x yes_y
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2021-02-15
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多