Objective
To extract data of interest and gather it in a list. The code runs well when run line by line, but when I run the block it does not work. I'm very grateful for your inputs to improve the code!
Data
iris <- iris %>%
mutate(id = ifelse(Species == "setosa" & Petal.Width <= 0.3, 12,
ifelse(Species == "setosa" & Petal.Width > 0.3, 14,
99)))
n12 <- c("a", "b", "c")
loadn12 <- data.frame(n12)
n14 <- c("d", "e", "f")
loadn14 <- data.frame(n14)
rm(n12, n14)
Code attempt
myfun <- function(x){
if(!nrow(filter(x, Species == "setosa")) == 0){
print("Check")
list <- list()
irischeck <- filter(iris, Species == "setosa")
ids <- unique(irischeck$id)
for(id in ids){
assign(paste0("data", id),
value = get(paste0("loadn", id)) %>% #Here I'll read files from a directory!
mutate(id = id))
list[[which(ids == id)]] <- get(paste0("data", id))
}
else{print("Don't check")
}
}
myfun(iris)
Desired output
For this example, I'd like to obtain a list containing two elements: (1) list[[1]] would be a the data frame n12 with an additional variable called id and indicating number 12 (2) list [[2]] would be a the data frame n14 with an additional variable called id and indicating number 14.
Aucun commentaire:
Enregistrer un commentaire