2021年3月23日星期二

If else condition to replace column values in R

I am trying to replace column values of df$status. The conditions are, any values that is 1 takes "CO", 2 takes "CA", 3 takes "MCI" and anything else takes "unknown". I tried this code below, but it is not giving me the expected result. What do I need to do with this if else condition here?

if (covars$STATUS==1){    covars$STATUS <- "CO"  } else if (covars$STATUS==2) {    covars$STATUS  <- "CA"  } else if (covars$STATUS==3) {    covars$STATUS  <- "MCI"  } else {    covars$STATUS  <- "unknown"  }  

data:

df <- structure(list(FID = structure(c(`1` = 1L, `2` = 1L, `3` = 1L,   `4` = 1L, `5` = 1L, `6` = 1L), .Label = "0", class = "factor"),       IID = structure(1:6, .Names = c("1", "2", "3", "4", "5",       "6"), .Label = c("07AD5724", "08AD10457", "08AD10956", "08AD10987",       "08AD11073", "08AD11218"), class = "factor"), COHORT = structure(c(`1` = 1L,       `2` = 1L, `3` = 1L, `4` = 1L, `5` = 1L, `6` = 1L), .Label = "CHOP_AA", class = "factor"),       SEX = structure(c(`1` = 3L, `2` = 2L, `3` = 3L, `4` = 1L,       `5` = 1L, `6` = 2L), .Label = c(" 1", " 2", "-9"), class = "factor"),       PC1 = structure(c(`1` = 5L, `2` = 1L, `3` = 6L, `4` = 2L,       `5` = 3L, `6` = 4L), .Label = c(" 0.0007", "-0.0054", "-0.0106",       "-0.0224", "-0.1090", "-9.0000"), class = "factor"), PC2 = structure(c(`1` = 1L,       `2` = 3L, `3` = 6L, `4` = 2L, `5` = 4L, `6` = 5L), .Label = c(" 0.0041",       " 0.0130", " 0.0161", "-0.0004", "-0.0164", "-9.0000"), class = "factor"),       PC3 = structure(c(`1` = 1L, `2` = 4L, `3` = 6L, `4` = 3L,       `5` = 2L, `6` = 5L), .Label = c(" 0.0073", " 0.0091", " 0.0145",       "-0.0104", "-0.0214", "-9.0000"), class = "factor"), STATUS = structure(c(`1` = 2L,       `2` = 1L, `3` = 3L, `4` = 1L, `5` = 1L, `6` = 2L), .Label = c(" 1",       " 2", "-9"), class = "factor"), PC4 = structure(c(`1` = 3L,       `2` = 2L, `3` = 6L, `4` = 4L, `5` = 1L, `6` = 5L), .Label = c(" 0.0073",       " 0.0431", "-0.0102", "-0.0210", "-0.0498", "-9.0000"), class = "factor"),       PC5 = structure(c(`1` = 1L, `2` = 5L, `3` = 6L, `4` = 2L,       `5` = 3L, `6` = 4L), .Label = c(" 0.0081", " 0.0123", "-0.0029",       "-0.0327", "-0.0350", "-9.0000"), class = "factor")), class = "data.frame", row.names = c("1",   "2", "3", "4", "5", "6"))  
https://stackoverflow.com/questions/66774181/if-else-condition-to-replace-column-values-in-r March 24, 2021 at 11:07AM

没有评论:

发表评论