Replace all NA with FALSE in selected columns in R

前端 未结 5 1811
挽巷
挽巷 2020-12-31 01:57

I have a question similar to this one, but my dataset is a bit bigger: 50 columns with 1 column as UID and other columns carrying either TRUE or NA

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 02:41

    Try this code:

    df <- data.frame(
      id = c(rep(1:19), NA),
      x1 = sample(c(NA, TRUE), 20, replace = TRUE),
      x2 = sample(c(NA, TRUE), 20, replace = TRUE)
    )
    replace(df, is.na(df), FALSE)
    

    UPDATED for an another solution.

    df2 <- df <- data.frame(
      id = c(rep(1:19), NA),
      x1 = sample(c(NA, TRUE), 20, replace = TRUE),
      x2 = sample(c(NA, TRUE), 20, replace = TRUE)
    )
    df2[names(df) == "id"] <- FALSE
    df2[names(df) != "id"] <- TRUE
    replace(df, is.na(df) & df2, FALSE)
    

提交回复
热议问题