How to impute a conditional row-wise imputation of a constant

43 Views Asked by At

I am somewhat of an R newbie, am struggling with writing code for what seems like simple logic, and would appreciate any help! I am trying to impute a constant value of 1 for NA cells in each row of my data set but only for rows that have 2 or less NA cells. Ultimately, I will also be computing a new column with row-wise means after imputation. If one line of code code automagically achieve all of these things, that would be great!

Here is an example data set to work with.

tData <- data.frame(subID=c(1001,1002,1003,1004),
b1=c(1,1,2,NA),
b2=c(NA,1,1,NA),
b3=c(NA,2,2,NA),
b4=c(2,NA,1,NA))

I have been looking at various base and dplyr code examples but am riding the struggle bus.

2

There are 2 best solutions below

2
TarJae On BEST ANSWER

We can do this like this:

library(dplyr)

tData %>% 
  mutate(across(-subID, ~ifelse(rowSums(is.na(tData[2:5])) <= 2 & is.na(.), 1, .))) %>%
  rowwise() %>%
  mutate(mean_value = mean(c_across(-subID), na.rm = TRUE))
 subID    b1    b2    b3    b4 mean_value
  <dbl> <dbl> <dbl> <dbl> <dbl>      <dbl>
1  1001     1     1     1     2       1.25
2  1002     1     1     2     1       1.25
3  1003     2     1     2     1       1.5 
4  1004    NA    NA    NA    NA     NaN  
0
jay.sf On

You can do this in these two lines.

tData[is.na(tData) & rowSums(is.na(tData)) <= 2] <- 1
tData |> cbind(row_means=rowMeans(tData[-1]))
#   subID b1 b2 b3 b4 row_means
# 1  1001  1  1  1  2      1.25
# 2  1002  1  1  2  1      1.25
# 3  1003  2  1  2  1      1.50
# 4  1004 NA NA NA NA        NA

Data:

tData <- structure(list(subID = c(1001, 1002, 1003, 1004), b1 = c(1, 1, 
2, NA), b2 = c(NA, 1, 1, NA), b3 = c(NA, 2, 2, NA), b4 = c(2, 
NA, 1, NA)), class = "data.frame", row.names = c(NA, -4L))