1

I'm trying to read a csv file and it looks like this upon doing a read.csv

df = read.csv("df.csv", header = FALSE, sep = ",", skipNul = TRUE)

  V1   V2   V3   V4
1 my 
2 Col1 Col2 Col3 Col4
3 1    2    3    a  
4 1    5    2    a
5 1    5    3    a

I had to set header = FALSE otherwise the file wouldn't be read due to the first row having that weird "my" string there.

I would like to set the column index to be Col1, Col2, Col3, Col4. I tried this but it doesn't work:

df <- df[-1,] #use negative indexing to remove first row

colnames[df] <- df[1,] #change colnames index

Output:

      Col1 Col2 Col3 Col4 
    2 Col1 Col2 Col3 Col4
    3 1    2    3    a  
    4 1    5    2    a
    5 1    5    3    a

How do I fix this to achieve what I want?

spidermarn
  • 959
  • 1
  • 10
  • 18
  • 5
    try `skip = 1, header = TRUE` in `read.csv` – Ronak Shah May 15 '19 at 02:34
  • 1
    You were close. By removing the first column of the last data.frame you would get closer. Then you would have to take care of the column types. Ronak's solution is for sure more elegant. – Roman Luštrik May 15 '19 at 05:26
  • Related post: https://stackoverflow.com/questions/23543825/r-read-table-how-can-i-read-the-header-but-also-skip-lines – zx8754 May 15 '19 at 06:20

1 Answers1

1

As @Ronak Shah pointed out, skip = 1 works and solved the problem

spidermarn
  • 959
  • 1
  • 10
  • 18