Reputation: 165
I would like to clarify my understanding here on both converting a file into CSV and also reading it. Let's use a dataset from R for instance, titled longley.
To set up a data frame, I can just use the write.table command as follows, right?
d1<-longley
write.table(d1, file="", sep="1,16", row.names=TRUE, col.names=TRUE)
Has this already become a data frame or am I missing something here?
Now let's say if I want to read this CSV file. Then would my code be something like:
read.table(<dframe1>, header=FALSE, sep="", quote="\"")
It seems like before that I have to use a function called setwd(). I'm not really sure what it does or how it helps. Can someone help me here?
Upvotes: 2
Views: 153
Reputation: 93811
longley
and, therefore, d1
are already data frames (type class(d1)
in the console). A data frame is a fundamental data structure in R. Writing a data frame to a file saves the data in the data frame. In this case, you're trying to save the data in the data frame in CSV format, which you would do like this:
write.csv(d1, "myFileName.csv")
write.csv
is a wrapper for write.table
that takes care of the settings needed for saving in CSV format. You could also do:
write.table(d1, "myFileName.csv", sep=",")
sep=","
tells R to write the file with values separated by a comma.
Then, to read the file into an R session you can do this:
df = read.csv("myFileName.csv", header=TRUE, stringsAsFactors=FALSE)
This creates a new object called df
, which is the data frame created from the data in myFileName.csv
. Once again, read.csv
is a wrapper for read.table
that takes care of the settings for reading a CSV file.
setwd
is how you change the working directory--that is, the default directory where R writes to and reads from. But you can also keep the current working directory unchanged and just give write.csv
or read.csv
(or any other function that writes or reads R objects) the full path to wherever you want to read from or write to. For example:
write.csv(d1, "/path/for/saving/file/myFileName.csv")
Upvotes: 1