R: Simplifying long ifelse statement

前端 未结 2 439
小蘑菇
小蘑菇 2021-01-25 15:04

I\'m trying to create new variables based on a procedure code variable with 2500+ values in a medical dataset to pull out the antibiotics, their dose, and route. I\'ve been abl

2条回答
  •  醉梦人生
    2021-01-25 15:54

    A base R approach for a simple option:

    # my dummy data
    df1 <- data.frame("v1" = c(LETTERS[1:10]), "v2" = rep(NA, 10))
    
    # step 1, fill the column with 0 (the else part of your code)
    df1[,'v2'] <- 0
    
    # step 2, create a vector containing ids you want to change
    change_vec <- c("A", "C", "D", "F")
    
    # step 3, use %in% to index and replace with 1
    df1[,'v2'][df1[,'v1'] %in% change_vec] <- 1
    

    In most cases this will be adequate, but be aware of the risks of using indexing vectors that contain numeric values.

    https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f

提交回复
热议问题