Reputation: 345
So I have a 100x20 data frame which contains NA values randomly. I also have a vector with the length of 20.
I want to replace all NA values for every specific column with the indices of the vector. So lets say all NA values in column 1 in my data frame should be replaced with the first value of my vector, all NA values in column 2 should be replaced with the 2nd value of my vector and so on.
I could do it with a for loop but I know I can do this much more easily. I have searched around for similar problems but cannot find any. If this is a duplicate then my appologies.
Upvotes: 2
Views: 636
Reputation: 887851
We can do an assignment by replicating the vector
i1 <- is.na(df)
df[i1] <- v1[col(df)][i1]
Or we can use
v1[col(df)]*is.na(df) + replace(df, is.na(df), 0)
Or we can use Map
to replace
the corresponding columns NAs with the vector
elements
df[] <- Map(function(x, y) replace(x, is.na(x), y), df, v1)
set.seed(24)
df <- as.data.frame(matrix(sample(c(NA, 1:5), 100*20, replace = TRUE), ncol = 20))
set.seed(48)
v1 <- sample(1:10, 20, replace = TRUE)
Upvotes: 4