Home > Software design >  Read table with columns of unequal row length by filling with NA
Read table with columns of unequal row length by filling with NA

Time:12-13

I am failing to a read a table with read.csv() as it has columns of different row lengths.

My data looks like this:

      x        y

1     cat      small
2     dog      medium
3     mouse    

I want to fill out the shorter columns with NA, so that I can create a data frame looking like this:

      x        y

1     cat      small
2     dog      medium
3     mouse    NA

The read.scv documentation has an argument "Fill=TRUE", but this function only deals with tables having rows of different column lengths.

Best regards, Rikki

CodePudding user response:

Try fread from the data.table package. This recognizes empty cells and fills them with NA.

The csv I've created for testing looks like:

a;b
1;1
2;2
3;3
;4
;5

R Code:

library(data.table)

fread(file.choose()) 

Output:

    a b
1:  1 1
2:  2 2
3:  3 3
4: NA 4
5: NA 5
  • Related