Jie Hu
Jie Hu

Reputation: 539

In R, how to read a special csv with some rows skipped the first value?

The data in Excel is like: enter image description here

You can see the first column Date has some value missing, but by default they are just following the first value.

How I can read this kind of csv file into R? Should I do a script to replace these missing values then read them or there's some options in read.csv() to deal with this? I checked the official manual but couldn't find one.

To be more clear, the target is to automatically add the missing date directly into the csv files:

enter image description here

Upvotes: 1

Views: 157

Answers (1)

lampros
lampros

Reputation: 581

Updated

you can use the na.strings parameter to replace the empty dates ("") with missing values (NA),

data = read.csv(your_file, header = TRUE, na.strings = c(""))

then,

data$Date = as.Date(data$Date)
data$Date = zoo::na.locf(data$Date)

to fill the missing values.

However, credit to @Taran, who commented your initial question, as I wasn't aware of the zoo::na.locf function.

Upvotes: 4

Related Questions