简体   繁体   中英

Recode NAs in multiple dataframe columns

I have multiple integer columns in a data frame, all with NAs that I need to recode to 0.

df1 <- as.data.frame(sapply(paste(sample(letters,50,T),sample(letters,10), sep=""), function(x) {sample(c(NA,0:5),10,T)} ))
df2 <- as.data.frame(sapply(paste(sample(letters,5,T),sample(letters,10,T), sep=""), function(x) {sample(letters[1:5],10,T)} ))
df <- cbind(df2,df1)

Producing an output like this... (only the first few columns of the 55 shown)

在此输入图像描述

I can go about recoding the NAs to 0 manually like df$col[is.na(df$col)] <- 0 for each column, but given that there are so many columns, it would take a while to type that all out.

How can I recode all of these NAs to 0 in a line or three?

(I realise I could melt the integer columns and then recode the one melted column, but I'd rather do this in base R)

你非常接近:

df[is.na(df)] <- 0

使用plyrcolwise元函数可以轻松实现:

dfZ=colwise(function(x)ifelse(is.na(x),0,x))(df)

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