Home:ALL Converter>How to count the number of non-empty fields in a delimited file?

How to count the number of non-empty fields in a delimited file?

Ask Time:2015-09-20T15:44:28         Author:Richie Cotton

Json Formatter

You can count the number of fields per line in a comma/tab/whatever delimited text file using utils::count.fields.

Here's a reproducible example:

d <- data.frame(
  x = c(1, NA, 3, NA, 5),
  y = c(NA, "b", "c", NA, NA),
  z = c(NA, "beta", "gamma", NA, "epsilon")
)

fname <- "test.csv"
write.csv(d, fname, na = "",  row.names = FALSE)
count.fields(fname, sep = ",")
## [1] 3 3 3 3 3 3

I want to calculate the number of non-empty fields per line. I can do this in a clunky way by reading in everything and counting the number of values that aren't NA.

d2 <- read.csv(fname, na.strings = "")
rowSums(!is.na(d2))
## [1] 1 2 3 0 2

I'd really like a way of scanning the file (like count.fields) so I can target specific sections to read in.

Is there a better way of counting the number of non-empty fields in a delimited file?

Author:Richie Cotton,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32677018/how-to-count-the-number-of-non-empty-fields-in-a-delimited-file
yy