【问题标题】:loop through a filter call in R循环通过 R 中的过滤器调用
【发布时间】:2022-11-02 20:05:10
【问题描述】:

我有一个名为“windows”的遗传数据数据框

glimpse(windows)
Rows: 3,000
Columns: 5
$ chrpos       <chr> "1:104159999-104168402", "1:104159999-104168402", "1:104159999-104168402"
$ target       <chr> "AMY2A", "CFD13", "PUTA"
$ name         <chr> "rs5753", "rs70530", "rs21111"
$ chr          <chr> "1", "1", "1"
$ pos          <int> 104560629, 104562750, 104557705

我想让它们按“目标”列中的行分隔数据框

AMY2A<- filter(windows, target == 'AMY2A')
write.table("am2ya.txt", header=T)

效果很好,但是对于“目标”的每个元素行来说都是很费力的

但是我如何遍历所有这些,然后将它们保存为文本文件,一口气?

list <- windows$target
for(i in list)
df.list[[i]]<-filter(windows, target == list[[i]])

这给出了错误:

Error in `filter()`:
! Problem while computing `..1 = target == list[[i]]`.
Caused by error in `list[[i]]`:
! subscript out of bounds

当我在谷歌上保存多个 txt 文件时,它只是出现了如何读取多个文本文件。

任何帮助都会很棒,谢谢!

【问题讨论】:

    标签: r loops for-loop tidy


    【解决方案1】:

    可能是这样的:

    lst <- windows$target
    
    for(i in seq_along(lst)){
      dat <- filter(windows, target == lst[[i]])
      write.table(dat, paste0(tolower(lst[[i]]), ".txt"))
    }
    
    

    【讨论】:

      【解决方案2】:

      或者,使用 tidyverse,类似

      windows %>% 
        group_by(target) %>% 
        group_walk(
          function(.x, .y) {
            write.table(.x, paste0(tolower(.y$target[1]), ".txt"))
          },
          .keep=TRUE
        )
      

      [未经测试的代码,因为您的问题不可重现。]

      .keep=TRUEtarget 列保留在文本文件中。如果这是不必要的,请随时删除它。详细信息在在线文档中。

      【讨论】:

        猜你喜欢
        • 2019-07-14
        • 2021-07-04
        • 2021-07-06
        • 2019-07-28
        • 2021-01-17
        • 2016-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多