Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle blank values while importing/reading data

Tags:

r

I have a data set with 3 variables. In these 3 variables 2 variables are filled with some data and third variable is empty (i.e., I don't have any information)

data1 <- structure(list(COL1 = structure(1:10, 
                                     .Label = c("A", "B", "C", "D", "E", 
                                                "F", "G", "H", "I", "J"), 
                                     class = "factor"), 
                    COL2 = 1:10, 
                    COL3 = c("", "", "", "", "", "", "", "", "", "")), 
               .Names = c("COL1", "COL2", "COL3"), 
               row.names = c(NA, -10L),
               class = "data.frame")

When I try to load this data set, R automatically converts empty cell to NA values. How can I read my data as is?

like image 999
RSK Avatar asked Mar 04 '26 18:03

RSK


1 Answers

You can specify colClasses=NULL for that column while reading the dataset.

  read.table('emptycell.txt', header=TRUE, fill=TRUE,
                colClasses=c('character', 'numeric', NULL))
  #   COL1 COL2 COL3
  #1     A    1     
  #2     B    2     
  #3     C    3     
  #4     D    4     
  #5     E    5     
  #6     F    6     
  #7     G    7     
  #8     H    8     
  #9     I    9     
  #10    J   10     

Or you can change the NA to '' after reading the dataset as mentioned by @KFB

  data1 <- read.table('emptycell.txt', header=TRUE, fill=TRUE)
  data1[is.na(data1)] <- ''
like image 180
akrun Avatar answered Mar 07 '26 08:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!