首页 > 解决方案 > R根据其他列值设置列值

问题描述

我需要根据其他列的值将列的值设置为 0 或 1。

如果它们为 0 或 NA,则新列应为 1。

我想过:

ifelse(df[,53:62]==0|NA, df$newCol <- 1, df$newCol <- 0)

但我最后我在新列中只得到 1

谢谢你的帮助

标签: r

解决方案


我认为 tidyverse 非常适合这个常见用例

library(tidyverse)

df_example <- matrix(c(0,1),ncol = 100,nrow = 100) %>% 
  as_tibble()


df_example %>% 
  mutate(across(.cols = 53:62,
                .fns = ~ if_else(.x == 0|is.na(.x),
                                 1,
                                 0))
  ) %>% 
  select(V54) # example**

推荐阅读