【问题标题】:I need to read a set of .CSV files in a folder by copying the header(First row) to a column variable and the second row as a header in R我需要通过将标题(第一行)复制到列变量并将第二行作为 R 中的标题来读取文件夹中的一组 .CSV 文件
【发布时间】:2021-02-01 21:09:53
【问题描述】:

我需要通过将标题(第一行)复制到列变量并将第二行作为 R 中的标题来读取文件夹中的一组 .CSV 文件。

我的输入格式是这样的

enter image description here

我的输出格式是这样的

Date = c('3/12/2019', '3/14/2019', '3/15/2019')
Number = c('24', '15.2', '27.1')
linc = c('A / B /C / D /E / F', 'A / B /C / D /E / F', 'A / B /C / D /E / F')
D1 = data.frame(Date, Number, linc)

抱歉,bas 问题的格式。我是初学者

【问题讨论】:

    标签: r dataframe csv read.csv


    【解决方案1】:

    以下函数从输入文件中读取一行,然后跳过一行并将其余行作为带有read.csv 的表读取。

    readSpecial <- function(con, newcol, ...){
      if(missing(newcol)) newcol <- "newcol"
      firstline <- readLines(con, n = 1)
      df1 <- read.csv(con, skip = 1, ...)
      df1[[newcol]] <- firstline
      df1
    }
    
    
    all.equal(D1, readSpecial("test.csv", "linc"))
    #[1] "Component “Number”: Modes: character, numeric"              
    #[2] "Component “Number”: target is character, current is numeric"
    

    结果不等于发布的数据,因为在我为测试创建的文件中,Number 列不在引号之间,因此它被读取为数字。

    【讨论】:

      【解决方案2】:

      我用for循环尝试过这种方式,它有效

      a <- list.files(path="",pattern="*.csv",recursive = T,full.names = T)
      
      for (i in a){
      
      b <- read.csv(i, skip = 0, header = F, nrows = 1, as.is= T)
      
      df=read.csv(i, skip = 1, header = T)
      
      df=df %>% mutate( new_col = b$V1 )
      
      Combined_file=rbind(Combined_file, df)
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-01-09
        • 2020-06-25
        • 1970-01-01
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多