【问题标题】:is there an r code that can select based on 3 columns and returns a value based on the options是否有可以基于 3 列选择并根据选项返回值的 r 代码
【发布时间】:2021-05-25 13:36:15
【问题描述】:

我想根据屋顶、墙壁和地板创建一个新的变量名称。如果任何选项的值为 1,则新变量赋值为 1,否则为 0。

roof<-c(1,1,1,0,1,0)
    wall<-c(0,1,1,0,0,0)
    floor<-c(1,1,1,0,1,0)
    data<-data.frame(roof,wall,floor)
    data
    data$code<-c(1,1,1,0,1,0)

【问题讨论】:

    标签: r if-statement dplyr


    【解决方案1】:

    你可以使用pmap:

    library(tidyverse)
    
    roof<-c(1,1,1,0,1,0)
    wall<-c(0,1,1,0,0,0)
    floor<-c(1,1,1,0,1,0)
    data<-data.frame(roof,wall,floor)
    
    #
    data %>%
      mutate(code_want = pmap_int(data %>%
                                    select(roof:floor) %>%
                                    mutate_all(as.logical), any))
    
    #   roof wall floor code code_want
    #1    1    0     1    1         1
    #2    1    1     1    1         1
    #3    1    1     1    1         1
    #4    0    0     0    0         0
    #5    1    0     1    1         1
    #6    0    0     0    0         0
    

    【讨论】:

      猜你喜欢
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多