问题
This is my data.
# A tibble: 10 x 6
id main s_0 s_1 s_2 s_3
<dbl> <fct> <fct> <fct> <fct> <fct>
1 1 5 75 A 4 110
2 2 NA NA NA NA NA
3 3 11 13 NA 7 769
4 4 NA NA NA NA NA
5 5 11 NA NA NA 835
6 6 13 39 NA 4 NA
7 7 NA NA NA NA NA
8 8 19 42 D 6 654
9 9 20 4 NA 7 577
10 10 NA NA NA NA NA
As you can see, the column main indicates that rows in the other columns (s_0: s_4) answered the questions or not. Ids 2,4,7 and 10 were not eligible for the rest, however, other participants can answer or miss (s_0:s_4). So I have a mix of NAs, I want to use a code that can identify the source of missing. The code that I am using mix all kind of missing :
library(dplyr)
library(forcats)
# Make sample data vars factors
dat <- dat %>%
mutate(across(starts_with("s_"), as.factor))
# Add 'No' as factor level
dat %>%
mutate(across(starts_with("s_"), fct_explicit_na, "No"))
While I want to have something like this:
# A tibble: 10 x 6
id main s_0 s_1 s_2 s_3
<dbl> <fct> <fct> <fct> <fct> <fct>
1 1 5 75 A 4 110
2 2 NO1 NO1 NO1 NO1 NO1
3 3 11 13 NO 7 769
4 4 NO1 NO1 NO1 NO1 NO1
5 5 11 NO NO NO 835
6 6 13 39 NO 4 NA
7 7 NO1 NO1 NO1 NO1 NO1
8 8 19 42 D 6 654
9 9 20 4 NO 7 577
10 10 NO1 NO1 NO1 NO1 NO1
回答1:
Try :
#Convert columns to characters
df[-1] <- lapply(df[-1], as.character)
#Find index of `NA` value in `main` column
inds <- is.na(df$main)
#Change all the columns to "NO1" in row inds
df[inds, -1] <- 'NO1'
#Change remaining NA values to "NO"
df[is.na(df)] <- 'NO'
df
# id main s_0 s_1 s_2 s_3
#1 1 5 75 A 4 110
#2 2 NO1 NO1 NO1 NO1 NO1
#3 3 11 13 NO 7 769
#4 4 NO1 NO1 NO1 NO1 NO1
#5 5 11 NO NO NO 835
#6 6 13 39 NO 4 NO
#7 7 NO1 NO1 NO1 NO1 NO1
#8 8 19 42 D 6 654
#9 9 20 4 NO 7 577
#10 10 NO1 NO1 NO1 NO1 NO1
来源:https://stackoverflow.com/questions/65095558/replace-na-in-a-series-of-variables-with-different-types-of-missing