Reputation: 348
Hello I am trying to export multiple csv's from my environment to take them over to matlab. In order to do this I found a helpful loop from Write data frames in environment into separate csv files however running this code includes the row numbers in the csv which I don't want. Can anyone tell me how I can stop this happening? I saw on this post Prevent row names to be written to file when using write.csv that you could use something like write.csv(t, "t.csv", row.names=FALSE)
but I don't know how to incorporate this into the loop. If possible I would also like to get rid of the column BIposterior$d
after using it to split the dataframes. Thank you.
## Read in csv
BIposterior<-read.csv("BIPDF.csv",header=TRUE)
## Get rid of useless columns
BIposterior$X.1=NULL
BIposterior$n=NULL
BIposterior$X=NULL
BIposterior$x=NULL
BIposterior$a=NULL
BIposterior$th0=NULL
BIposterior$th1=NULL
## Create a loop to create separate data frames
for(i in unique(BIposterior$d)) {
nam <- paste("BIposterior", i, sep = ".")
assign(nam, BIposterior[BIposterior$d==i,])
}
## Export all of the csvs
files <- mget(ls())
for (i in 1:length(files)){
write.csv(files[[i]], paste(names(files[i]), ".csv", sep = ""))
}
### Data
structure(list(counts = c(0.00000762700016727025, 0.0000109607070538136,
0.0000154982683282787, 0.0000215453927859112, 0.0000294581590232964,
0.0000396276435633489), d = c(1L, 1L, 1L, 1L, 1L, 1L), year = c(2002.25707698199,
2002.27255361611, 2002.28803025023, 2002.30350688435, 2002.31898351848,
2002.3344601526)), row.names = c(NA, 6L), class = "data.frame")
Upvotes: 0
Views: 1830
Reputation: 257
I wasn't planning on writing this as an answer but since you apparently can't comment when you are new to this site, I will do so anyway. Sindri already replied to the first part, add row.names = FALSE after the name argument.
write.csv(files[[i]], paste(names(files[i]), ".csv", sep = ""), row.names=FALSE)
To drop the column that you don't need (which is what I was actually planning to comment on) you can simply write
BIposterior <- BIposterior[-x]
when you don't need d anymore, with x being the column number of d, so if d is the eigth column x would be eight. This overwrites BIposterior with a new version of BIposterior that doesn't have the xth column in it anymore.
Upvotes: 4