I need to count the NAs elements in a CSV file containing numeric values and NAs. Using read.csv, r automatically reads them all as character, therefore it's impossibile to detect how many NAs there are. How can i fix that?
Asked
Active
Viewed 178 times
-2
-
1This question is challenging to provide help with since it doesn't provide any information about what the data look like. What do the NA strings look like in the CSV file?ave you tried anything? look into `read.csv(filepath, na.strings = c("NA")` and fill the `c()` with whatever strings you have that represent NA – jpsmith Sep 06 '22 at 16:40
-
Please provide enough code so others can better understand or reproduce the problem. – Community Sep 06 '22 at 21:07
1 Answers
0
An approach using which
:
x = c(1,2,3)
y = c(6,5,4)
z = c(NA, 8, NA)
df1 <- data.frame(x,y,z)
# which has arr.ind option that returns locations by row/column
NA_idx <- which(is.na(df1) == TRUE, arr.ind = TRUE)
NA_idx
row col
[1,] 1 3
[2,] 3 3
This may not be so directly useful to the 'how many of x', 'how many of NA', so perhaps
length(which(is.na(unlist(df1)==TRUE)))
[1] 2
length(unlist(df1))
[1] 9
length(unlist(df1)) - length(which(is.na(unlist(df1)==TRUE)))
[1] 7

Chris
- 1,647
- 1
- 18
- 25