1
votes

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?

1
try skip = 1, header = TRUE in read.csvRonak Shah
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

1 Answers

1
votes

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