user3262756
user3262756

Reputation: 679

Function with if else statement that contains a for loop

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 the data frame n12 with an additional variable called id and indicating number 12 (2) list [[2]] would be the data frame n14 with an additional variable called id and indicating number 14.

Upvotes: 0

Views: 49

Answers (1)

Robert
Robert

Reputation: 5152

Is that what you want?

myfun <- function(x){
  list <- list()
  if(!nrow(filter(x, Species == "setosa")) == 0){ # x=iris
    print("Check")
    #list <- list()
    irischeck <- filter(iris, Species == "setosa")
    ids <- unique(irischeck$id)
    for(id in ids){  #id=ids[1]
      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")
  }
  list
}

  res = myfun(iris)

  # > res
  # [1] "Check"
  # [[1]]
  # n12 id
  # 1   a 12
  # 2   b 12
  # 3   c 12
  # 
  # [[2]]
  # n14 id
  # 1   d 14
  # 2   e 14
  # 3   f 14

Upvotes: 1

Related Questions