Questions about these two sets of codes

Hello, I am a newbie in R, and would like to learn the language. I really can't wrap my head round the codes I listed below and how the outcomes are different. Can someone please explain?

cats<-data.frame(coat=c("calico","black","tabby"),
weight=c(2.1,5.0,3.2),
likes_string=c(1,0,1))

write.csv(x=cats,file="data/feline-data.csv", row.names=TRUE)
cats<-read.csv(file="data/feline-data.csv")

So, here if you put "cats", you get this table
X coat weight likes_string
1 1 calico 2.1 1
2 2 black 5.0 0
3 3 tabby 3.2 1

However, if you call the statement "FALSE"
cats<-data.frame(coat=c("calico","black","tabby"),
weight=c(2.1,5.0,3.2),
likes_string=c(1,0,1))

write.csv(x=cats,file="data/feline-data.csv", row.names=FALSE)
cats<-read.csv(file="data/feline-data.csv")

You get
coat weight likes_string
1 calico 2.1 1
2 black 5.0 0
3 tabby 3.2 1

Why the "TRUE" code would not provide me an error message instead since the row names are different?
Thanks so much!

I'm not sure that I understand your question. It's behaving exactly as it should.

Here's from the documentation:

row.names
either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.

So, you can specify row.names as TRUE, FALSE or a character vector of same length as of the number of rows. In the 1st case, it'll add indexing 1, 2, ... in the first column, and hence the CSV will contain one extra column than your object. In the 2nd case, there will be no extra column. In the final case, there will be an extra column, but that will contain elements of the specified character vector.

See below:

cats <- data.frame(coat = c("calico", "black", "tabby"),
                   weight = c(2.1, 5.0, 3.2),
                   likes_string = c(1, 0, 1))

write.csv(x = cats,
          file = "feline-data-1.csv",
          row.names = TRUE)
(cats_1 <- read.csv(file = "feline-data-1.csv"))
#>   X   coat weight likes_string
#> 1 1 calico    2.1            1
#> 2 2  black    5.0            0
#> 3 3  tabby    3.2            1

write.csv(x = cats,
          file = "feline-data-2.csv",
          row.names = FALSE)
(cats_2 <- read.csv(file = "feline-data-2.csv"))
#>     coat weight likes_string
#> 1 calico    2.1            1
#> 2  black    5.0            0
#> 3  tabby    3.2            1

write.csv(x = cats,
          file = "feline-data-3.csv",
          row.names = paste("Index", 1:3))
(cats_3 <- read.csv(file = "feline-data-3.csv"))
#>         X   coat weight likes_string
#> 1 Index 1 calico    2.1            1
#> 2 Index 2  black    5.0            0
#> 3 Index 3  tabby    3.2            1

Created on 2019-02-27 by the reprex package (v0.2.1)

Hope this helps.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.