Quick replace of NA - an error or warning

后端 未结 3 1952
Happy的楠姐
Happy的楠姐 2021-01-13 03:59

I have a big data.frame called \"mat\" of 49952 obs. of 7597 variables and I\'m trying to replace NAs with zeros. Here is and example how my data.frame looks like:



        
相关标签:
3条回答
  • 2021-01-13 04:25

    If suspect that some of your columns are factor, you can use the following code to detect and change them to numeric.

    inx <- sapply(mat, inherits, "factor")
    mat[inx] <- lapply(mat[inx], function(x) as.numeric(as.character(x)))
    

    Then try the following.

    mat[] <- lapply(mat, function(x) {x[is.na(x)] <- 0; x})
    mat
    

    And here's the data.

    mat <-
    structure(list(A = c(1L, 0L, 0L, NA, 0L, 1L, 0L), B = c(1L, 0L, 
    0L, NA, 1L, 1L, 0L), C = c(0L, 1L, 0L, NA, 0L, 1L, 1L), E = c(NA, 
    NA, NA, NA, 1L, 0L, 0L), F = c(NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_), D = c(0L, 0L, 1L, NA, 
    0L, 0L, 1L), Q = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_), Z = c(NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_)), .Names = c("A", "B", "C", "E", 
    "F", "D", "Q", "Z"), row.names = c("1", "2", "3", "4", "5", "6", 
    "7"), class = "data.frame")
    
    0 讨论(0)
  • 2021-01-13 04:32

    See my detailed answer here.

    #install.packages("xlsx")
    library(xlsx)
    extracted_df <- read.xlsx("test.xlsx", sheetName='Sheet1', stringsAsFactors=FALSE)
    # Replace all NAs in a data frame with "G" character
    extracted_df[is.na(extracted_df)] <- "G"
    
    0 讨论(0)
  • Try the following:

    mat %>% replace(is.na(.), 0)
    
    0 讨论(0)
提交回复
热议问题