My lapply function cannot continue because of an error. What I noticed is because the column with which.max are gone in the column when there is no data for it, therefore lapply do not continue. If I am not explaining it well, here's the data and script:
data:
| store | fruit | color | start | end |
|---|---|---|---|---|
| Nina | banana | yellow | 1 | 9 |
| Lana | apple | red | 2 | 3 |
| Nina | grapes | green | 4 | 2 |
| Nina | banana | green | 4 | 7 |
| Lana | banana | yellow | 3 | 6 |
| Lana | apple | green | 2 | 5 |
| Lana | grapes | purple | 3 | 4 |
| Nina | grapes | purple | 2 | 3 |
and the script:
library(readr)
library(dplyr)
library(tidyverse)
list = c("apple", "banana", "mango", "grapes")
data=read_tsv("/home/polen/Desktop/data.tsv", col_names = TRUE)
group_func <- function(list) {
df <- data %>% filter(fruit == {{list}}) %>%
group_by(fruit) %>%
summarise(color = names(which.max(table(color))), min_start = min(start), max_end = max(end)) %>% select(fruit,color,min_start)
assign(list, df, envir = .GlobalEnv)
}
lapply(list, group_func)
this will return two files: apple and banana and an error "Column color doesn't exist."
However, if I remove the select function:
list = c("apple", "banana", "mango", "grapes")
data=read_tsv("/home/polen/Desktop/data.tsv", col_names = TRUE)
group_func <- function(list) {
df <- data %>% filter(fruit == {{list}}) %>%
group_by(fruit) %>%
summarise(color = names(which.max(table(color))), min_start = min(start), max_end = max(end))
assign(list, df, envir = .GlobalEnv)
}
lapply(list, group_func)
it will return 4 files: apple, banana, mango and grapes. Mango having only 3 variables (which causes the error in lapply).
What I want is to either:
- skip the error so it will continue to the next loop.
- retain the column that was removed in summarise so the loop will continue.
I tried tryCatch but I am not able to make it work, especially since (although not included in my above script), I am exporting those files to my computer. Although maybe it will work, I'm just really noob about it.
I will really appreciate help for this. Thank you!