2012-08-04 36 views
5

L'immagine allegata mostra parte di un dataframe che ho appena importato in R da un file excel. Nelle celle che sono vuote, ho bisogno di inserire "NA". Come posso inserire NA in qualsiasi cella che è vuota (lasciando le celle già popolate da sola)?Inserire valori NA in dataframe

enter image description here

risposta

16

La domanda migliore è come posso leggere in R in modo che le cellule mancanti saranno già NA s.

Forse hai usato qualcosa di simile:

read.csv(file, header=FALSE, strip.white = TRUE, sep=",") 

Specificare le NA corde come questo, quando lo si legge in:

read.csv(file, header=FALSE, strip.white = TRUE, sep=",", 
    na.strings= c("999", "NA", " ", "")) 

per rispondere alla tua domanda in realtà. Questo approccio potrebbe funzionare:

#making fake data on a Saturday morning 
dat <- data.frame(matrix(sample(c("", LETTERS[1:4]), 200, 
    replace=T, c(.6, rep(.1, 4))), 20)) 

#function to replace blanks with missing 
blank2na <- function(x){ 
    z <- gsub("\\s+", "", x) #make sure it's "" and not " " etc 
    x[z==""] <- NA 
    return(x) 
} 

#apply that function 
data.frame(sapply(dat, blank2na)) 
Problemi correlati