简体   繁体   中英

Replace NA values in a data frame column with values with elements from a vector

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.

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)

data

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM