r - 在二进制列中插入另一列的值

标签 r

有一个像这样的数据框:

    data.frame(previous = c(1,2,2,1,3,3), `next` = c(1,1,2,3,1,3),
    col1_1 = c(1,0,0,0,0,0),
    col1_2 = c(0,0,0,0,0,0),
    col1_3 = c(0,0,0,1,0,0),
    col2_1 = c(0,1,0,0,0,0),
    col2_2 = c(0,0,1,0,0,0),
    col2_3 = c(0,0,0,0,0,0),
    col3_1 = c(0,0,0,0,1,0),
    col3_2 = c(0,0,0,0,0,0),
    col3_3 = c(0,0,0,0,0,1), id = c(1,2,3,4,5,6), salary = c(30,20,40,10,40,80))

如何检查列,直到从 col 开始插入工资列的值(其中 1 存在)。

这里是预期的输出:

    data.frame(previous = c(1,2,2,1,3,3), `next` = c(1,1,2,3,1,3),
    col1_1 = c(30,0,0,0,0,0),
    col1_2 = c(0,0,0,0,0,0),
    col1_3 = c(0,0,0,10,0,0),
    col2_1 = c(0,20,0,0,0,0),
    col2_2 = c(0,0,40,0,0,0),
    col2_3 = c(0,0,0,0,0,0),
    col3_1 = c(0,0,0,0,40,0),
    col3_2 = c(0,0,0,0,0,0),
    col3_3 = c(0,0,0,0,0,80), id = c(1,2,3,4,5,6), salary = c(30,20,40,10,40,80))

最佳答案

我们可以使用mutate_at将其应用于各个列,使用ifelse并将1替换为相应的salary值。

library(dplyr)
df %>% mutate_at(vars(starts_with('col')), ~ifelse(. == 1, salary, .))

#  previous next. col1_1 col1_2 col1_3 col2_1 col2_2 col2_3 col3_1 col3_2 col3_3 id salary
#1        1     1     30      0      0      0      0      0      0      0      0  1     30
#2        2     1      0      0      0     20      0      0      0      0      0  2     20
#3        2     2      0      0      0      0     40      0      0      0      0  3     40
#4        1     3      0      0     10      0      0      0      0      0      0  4     10
#5        3     1      0      0      0      0      0      0     40      0      0  5     40
#6        3     3      0      0      0      0      0      0      0      0     80  6     80

或者以 R 为基数:

cols <- grep('^col', names(df))
df[cols] <- lapply(df[cols], function(x) ifelse(x == 1, df$salary, x))

关于r - 在二进制列中插入另一列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102998/

相关文章:

R 无法在 centos 6.5 上安装软件包

r - 输入密码后启动 Shiny 应用程序

r - 如何更新 Shiny 的 fileInput 对象?

r - 可以关注多列时过滤行

r - 连续数字之间划线

R 包 CRAN 注释,用于测试中的包依赖项和警告

r - 如何在R中的绘图标签中写每立方米的平方微米

r - 过滤任何命令时 group_by 变慢

r - 在 dplyr 的 mutate_at 中按名称排除列

string - 在R中将字符串拆分为多行