从列表

时间:2018-03-12 19:50:20

标签: r

我有一段代码正在读取许多数据帧,然后对它们进行rbinding

data.files = paths %>% ##takes the names of all the objects that I want to read in
  map(read.csv) %>% ##this reads all the correctly named .csv files into a list object
  reduce(rbind) ##reduces them all from the list into a single dataframe by rbind

其中paths是要读入的.csv文件名称的向量。但问题是许多这些对象缺少单个列LaserEnergy,这使得rbind失败。此列对我的分析并不重要,并且是早期数据处理的剩余部分。有没有办法让我可以通过删除列中包含该列的每个对象的列,或者将一个空列添加到正确位置的空列中?

替代方案是我浏览超过2000个文件并手动添加或删除列。

2 个答案:

答案 0 :(得分:4)

这样的东西?如果没有数据示例,很难确定哪些内容可以正常工作,但使用purrr::map_dfr这是map的简写,那么bind_rows应避免出错。如果所有列表元素中都没有列,则bind_rows不会抛出错误,它只会填充NA。然后,您可以从结果数据框中删除不需要的列。

library(tidyverse)
data.files <- paths %>%
    map_dfr(read_csv) %>%
    select(-LaserEnergy)

答案 1 :(得分:1)

最终为我工作的是,我必须使用data.table

data.files <- paths %>%
   map(read._csv) %>%
   rbindlist(fill = T)  ##This function is from the data.tables package, fill = T tells it to fill missing columns with NA

出于某种原因,read_csv在与map_dfr()一起使用时不喜欢列类,并且试图强制列进入它们不应该的类。我在文档中找不到任何可以解决它的内容(尝试指定col_types对我不起作用