【问题标题】:How can I re-write this for-loop with lapply如何用 lapply 重写这个 for 循环
【发布时间】:2019-09-13 15:34:51
【问题描述】:

我正在尝试用 lapply 替换 R 中的 for 循环。

Table <- c("Filepath1","Filepath2")
Conditions c<- c("Yes","No")

for (i in 1:length(Table)){

Df[[i]] <- readxl::read_xlsx(Table[i])
Df[[i]]$Condition <- Conditions[i]

}

因此,这会获取 Table 中的第一个元素,将其读入 R,然后将一列添加到与条件中的第一个元素对应的表中。

使用 lapply 我可以通过以下方式添加表格:

lapply(Table, readxl::read_xlsx)

我可以说:

Df[[1]]$Conditions <- Conditions[1]
Df[[2]]$Conditions <- Conditions[2]

但是如何在不使用 for 循环的情况下添加这个额外的列?

【问题讨论】:

  • 类似:lapply(seq_along(Conditions), function(x) {res &lt;- read_excel(list.files(pattern = ".*xlsx")[x]) res$Cond &lt;- Conditions[x] head(res) })。这假定文件表和条件向量的长度相等。它还假设您将所有内容都放在同一个目录中。
  • 您可以将 read_excel 替换为 read_xlsx。我实际上在本地使用了read.csv,因为我没有可用的 xlsx 文件。 :)
  • 我喜欢你的回答 :) 但不幸的是这些文件位于不同的目录中。
  • 用带有文件路径的向量替换 list.files。

标签: r for-loop lapply


【解决方案1】:

您可以使用mapply 遍历这两个对象(表和条件)。未经测试:

mapply(FUN = function(tbl, cnd) {
  out <- readxl::read_excel(tbl)
  out$Condition <- cnd
  out
}, tbl = Table, cnd = Conditions)

【讨论】:

  • 您缺少参数。另外,请查看 transformwithin 以获得单线。
  • 呸,你是对的参数。对不起,我不太在乎单线。
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2021-11-14
  • 2022-01-15
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
相关资源
最近更新 更多