【问题标题】:Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘"function"’ to a data.frameas.data.frame.default(x[[i]], optional = TRUE) 中的错误:无法将类“函数”强制转换为 data.frame
【发布时间】:2021-11-13 09:06:45
【问题描述】:

我一直在尝试合并文件,每次尝试运行时都会遇到各种错误错误

list.files(path = "~/Documents", full.names = FALSE) %>% lapply(read_csv) %>%  :  could not find function "%>%"
> write.csv(data, file = "Fecundity.csv", row_names = FALSE)
Error in utils::write.table(data, file = "Fecundity.csv", row_names = FALSE,  : 
unused argument (row_names = FALSE)

> write.csv(data, file = "Fecundity.csv", row.names = FALSE)
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class ‘"function"’ to a data.frame
> write.csv(data, file = "Fecundity.csv", row.names = TRUE)
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class ‘"function"’ to a data.frame

这是代码

library(data.table)
setwd(/cloud/project/Data sheets)
files <- list.files(pattern = ".cvs")
temp <- lapply(files, fread, sep= ".")
data <- rbindlist(temp)
write.csv(data, file = "Fecundity.csv", row.names = FALSE)`

【问题讨论】:

  • 您可能没有分配给data,并且data 已经作为"function" 对象存在。
  • “找不到函数”%>%”可能源于您需要首先使用library(dplyr)library(tidyverse)(安装和)加载dplyr 包。在末尾%>% 管道,您应该将生成的对象分配给对象“数据”,如下所示:data &lt;- list.files(&lt;code&gt;) %&gt;% lapply(&lt;code&gt;)。在编写data 之前,请确保它实际上是一个 data.frame 而不是一个列表(通常返回由lapply())。使用str(data)检查类和结构

标签: r csv


【解决方案1】:

这样做。

library(data.table)
library(fs)


files = dir_ls("csvFiles", regexp = "\\.csv$")
if(length(files)>0){
  for(i in 1:length(files)){
    lines = fread(text = files[i], sep = "|", header=FALSE)
    fwrite(lines, "csvFiles/Fecundity.csv", append = TRUE)
  }
}

这是我所知道的最快的方法。此代码将在几秒钟内读取数千个文件!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多