具有包含for循环的if else语句的函数

时间:2018-08-13 16:04:07

标签: r list for-loop if-statement dplyr

客观

提取感兴趣的数据并将其收集在列表中。 当一行一行地运行时,代码运行良好,但是当我运行该块时,它无法运行。 非常感谢您为改进代码所做的贡献!

数据

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)

代码尝试

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)

所需的输出

对于此示例,我想获取一个包含两个元素的列表: (1)list [[1]]将是数据帧n12,具有名为id的附加变量,并指示数字12(2)list [[2]]将是数据帧n14,具有名为id的附加变量,并指示数字14

1 个答案:

答案 0 :(得分:1)

这就是你想要的吗?

$current_staff_type => SELECT * FROM staff WHERE staff_id = $staff_id

if($current_staff_type == $updated_staff_type){
    //don't update
    return
}

SELECT * FROM staff WHERE staff_type = $updated_staff_type

if(num_of_rows > 0){
    //the type you're going to update already exists
    return
} else{
    //update
}
if num_of_rows > 0 //cannot insert, staff_type already exists