-1

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.

My input format is like this

enter image description here

My output format would be like this

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)

Sorry for bas question format. I am a beginner

2 Answers2

0

The following function reads one line from the input file, then skips one line and reads the rest as a table with 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"

The result is not equal to the posted data because in the file that I created for tests column Number was not between quotes and therefore it was read in as numeric.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

I tried this way using for loop, it worked

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)

}