Abhishek Wadhawan
Abhishek Wadhawan

Reputation: 31

Write CSV file with two columns in R loop (append)

I have some other complex script which is working fine, except for giving trouble in writing to a csv file. Let's say here as an example that I want k and j here to be present in 20 rows, k being in one column and j being in the second.

for (i in 1:20)
{
    k = i+2;
    j = i+20;
    m= data.frame(k,j)
    write.csv(m,file="Dummy.csv",append=TRUE)
    print(m)
}

The problem with this is, it is writing only the final value of m into the csv, even when the append is set to TRUE

And my question here is, do I need to make 'm' as a dataframe, matrix or a vector?

(Consider k and j to be particular changing text strings, which I am trying to wite in a CSV extracting from a corpus)

The following is the output of the CSV file:

"","k","j" "1",22,40

Upvotes: 1

Views: 3083

Answers (1)

Mhairi McNeill
Mhairi McNeill

Reputation: 1981

You can't use append = TRUE with write.csv. The idea is that it should be hard to mess up write.csv and do something you don't want to.

You can use it with write.table, giving this solution:

for (i in 1:20)
{
  k = i+2;
  j = i+20;
  m = data.frame(k,j)
  write.table(m, file="Dummy.csv",
              append=TRUE,
              col.names = FALSE,
              sep = ',')
  print(m)
}

Notice you have the miss out column names otherwise you get column names added in every iteration of the loop.

But, a better idea would be to build up the dataframe in parts and write it to a csv at the end.

m <- data.frame(NULL)
for (i in 1:20)
{
  k <- i+2;
  j <- i+20;
  m <- rbind(m, data.frame(k,j))
}

write.csv(m, file="Dummy2.csv")

Upvotes: 3

Related Questions