【问题标题】:Function with if else statement that contains a for loop带有包含 for 循环的 if else 语句的函数
【发布时间】:2018-08-13 16:04:06
【问题描述】:

目标

提取感兴趣的数据并将其收集到一个列表中。 代码在逐行运行时运行良好,但是当我运行该块时它不起作用。 非常感谢您对改进代码的投入!

数据

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]] 将是具有称为 id 的附加变量并指示编号 14 的数据帧 n14 .

【问题讨论】:

  • 想要的输出?

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


【解决方案1】:

这是你想要的吗?

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

【讨论】:

  • 谢谢罗伯特,这正是我想要的,但我想在环境中有一个包含两个数据框的实际列表对象。有什么建议吗?
  • 非常感谢,正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多