An option is to get an index of the NA
elements in the column, then use sample
with size
specified as the number of NA elements to replace those NA with the male
or female
sampled
i1 <- is.na(df1$col1)
df1$col1[i1] <- sample(c('male', 'female'), size = sum(i1), replace = TRUE)
-output
df1
# col1 col2
#1 a 1
#2 female 2
#3 b 3
#4 male 4
#5 a 5
#6 c 6
#7 female 7
data
df1 <- data.frame(col1 = c('a', NA, 'b', NA, 'a', 'c', NA), col2 = 1:7)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…