代码之家  ›  专栏  ›  技术社区  ›  jhyeon

在R中使用特定条件对多个列进行变异

  •  2
  • jhyeon  · 技术社区  · 7 年前

    M1  M2  M3 UCL
    1   2   3   1.5
    

    如果M1大于UCL,则MM1将为“UP”,否则为“NULL”

    如果M2大于UCL,则MM2将为“向上”,否则为“零”

    如果M3大于UCL,则MM3将“向上”,否则为“NULL”

    M1  M2  M3 UCL   | MM1  MM2 MM3
    1   2   3   1.5  | NULL UP  UP
    

    2 回复  |  直到 7 年前
        1
  •  5
  •   meenaparam    3 年前

    dplyr 解决方案注意,为新变量添加后缀更容易,例如获取 M1_M 而不是 MM1 。但是,您可以设置 colnames 之后,如果您希望重命名它们(参见例如。 here 关于如何做到这一点)。

    我将结果显示为 tibble UP 和一个 NA 在其中,它将从逻辑类型更改为字符类型。

    library(dplyr)
    
    textdata <- "M1  M2  M3 UCL
    1   2   3   1.5"
    
    mydf <- read.table(text = textdata, header = T)
    
    mydf %>% 
        mutate_at(vars(starts_with("M")), funs(M = ifelse(. > UCL, "UP", NA))) %>% 
        tibble::as.tibble()
    
    # A tibble: 1 x 7
         M1    M2    M3   UCL  M1_M  M2_M  M3_M
      <dbl> <dbl> <dbl> <dbl> <lgl> <chr> <chr>
    1     1     2     3   1.5    NA    UP    UP
    
        2
  •  1
  •   Florian    3 年前

    带基数R:

    dt <- read.table(text="M1  M2  M3 UCL
    1   2   3   1.5",header=T)
    
    ncols <- ncol(dt)
    dt <- cbind(dt, ifelse(subset(df, select=M1:M3) > dt[,"UCL"], "UP", "NULL"))
    colnames(dt)[ncols:ncol(dt)] = paste0("M", colnames(dt)[ncols:ncol(dt)])
    

       M1 M2 M3  UCL  MM1 MM2 MM3
    1   1  2  3  1.5 NULL  UP  UP