5

Inspired by Prevent row names to be written to file when using write.csv, I am curious if there a way to ignore the index column in R using the read.csv() formula. I want to import a text file into an RMarkdown document and don't want the row numbers to show in my HTML file produced by RMarkdown.

Running the following code

write.csv(head(cars), "cars.csv", row.names=FALSE)

produces a CSV that looks like this:

speed   dist
 4      2
 4      10
 7      4
 7      22
 8      16
 9      10

But, if you read this index-less file back into R (ie, read.csv("cars.csv")), the index column returns:

.   speed dist
1    4     2
2    4     10
3    7     4
4    7     22
5    8     16
6    9     10

I was hoping the solution would be as easy as including row.names=FALSE to the read.csv() statement, as is done with write.csv(), however after I run read.csv("cars.csv", row.names=FALSE), R gets sassy and returns an "invalid 'row.names' specification" error message.

I tried read.csv("cars.csv")[-1], but that just dropped the speed column, not the index column.

How do I prevent the row index from being imported?

Community
  • 1
  • 1
Hip Hop Physician
  • 252
  • 1
  • 3
  • 12
  • 1
    Is the difference between `row.names=FALSE` and `row.names="FALSE"` a typo in your question or in your code? – IMSoP Apr 28 '15 at 19:48
  • fat fingers; I'll update my question – Hip Hop Physician Apr 28 '15 at 19:52
  • @HipHopPhysician, I doubt that there is a way that would allow you to remove the indices. This is something that R IDEs, including RStudio, will always have. But if you find a solution to remove the indices, please do share! – Abdou Apr 28 '15 at 20:03

2 Answers2

3

If you save your object, you won't have row names.

     x <- read.csv("cars.csv")

But if you print it (to HTML), you will use the print.data.frame function. Which will show row numbers by default. If I use the following (as last line) in my markdown chunk, I didn't have row numbers displayed:

 print(read.csv("cars.csv"), row.names = FALSE)
Arcoutte
  • 810
  • 4
  • 16
2

Why?: This problem seems associated with a previous subset procedure that created the data. I have a file that keeps coming back with a pesky index column as I round-trip the data via read/write.csv.

Bottom Line: read.csv takes a file completely and outputs a dataframe, but the file has to be read before any other operation, like dropping a column, is possible.

Easy Workaround: Fortunately it's very simple to drop the column from the new dataframe:

df <- read.csv("data.csv")
df <- df[,-1]
childerino
  • 331
  • 2
  • 5