How to import a csv with blank cells

Viewed 47

When I import a csv, it appears as a dataframe with this format

firstcol <- c("A","","D","Z")
seccol <- c("W","Y","C","")
thircol <- c("","H","Q","M")

df <- data.frame(firstcol,seccol,thircol)

#    > df
#      firstcol seccol thircol
#    1        A      W        
#    2               Y       H
#    3        D      C       Q
#    4        Z              M

When I type levels(df$firstcol)

The output is: [1] "" "A" "D" "Z"

How can I import my csv such that the cells are being read as empty cells and not as an observation?

2 Answers

We can use na.strings = "" so that the blank cells will be read as NA

df1 <- read.csv('file.csv', na.strings = '', 
       strip.white = TRUE, stringsAsFactors = FALSE)

You can read the values as NA while reading the .csv

df1 <- read.csv('file.csv', header=T, na.strings=c(""))
Related