jeudi 2 septembre 2021

Checking the number of rows for each dataframe in a list which includes empty dataframes

I have data as follows:

dataset = list()
a <- c(1,2,3)
b <- c(1,2,3)
country <- c("A","B","C")
source_country <-  c("D","D","D")
dataset[[1]] <- data.frame(a,b,country, source_country)
a <- c(NA)
b <- c(NA)
country <- c(NA)
source_country <- c(NA)
dataset[[2]] <- data.frame(a,b,country, source_country)

I want to get the names of the countries for which the amount of rows in the dataframe exceeds 1. For some reason the code below works on my example code, but not on my actual code:

for (i in 1:length(dataset)) {
  if (nrow(dataset[[i]]) > 1) {
    print(dataset[[i]][["country"]][[1]])
  }   
}

On my actual code, it says Error in if (nrow(dataset[[i]]) > 1) { : argument is of length zero. To surpass this I tried:

# https://stackoverflow.com/questions/27350636/r-argument-is-of-length-zero-in-if-statement
# Gives countries for which the limit was exceeded
for (i in 1:length(dataset)) {
  if (!is.null(dataset[[i]]) {
    print ("no data") 
  } else if (nrow(dataset[[i]]) > 1) {
      print(dataset[[i]][["country"]][[1]])
  }   
}

But then I get the following errors:

> for (i in 1:length(dataset)) {
+     if (!is.null(dataset[[i]]) {
Error: unexpected '{' in:
"for (i in 1:length(dataset)) {
    if (!is.null(dataset[[i]]) {"
>         print ("no data") 
[1] "no data"
>     } else if (nrow(dataset[[i]]) > 1) {
Error: unexpected '}' in "    }"
>         print(dataset[[i]][["Reporter"]][[1]])
Error in dataset[[i]] : subscript out of bounds
>     }   
Error: unexpected '}' in "    }"
> }

Could anyone lend me a hand?

Aucun commentaire:

Enregistrer un commentaire