anz
anz

Reputation: 1042

R : Write CSV that has varying row values

I am trying to write to a csv file from R, that has varying number of row values,

*for example*,
1,2,3,4,5
2,3,6
2,3
4,3,4,5

I have tried 3 possible attempts, but failed one way or the other.

  1. I created a data frame that has 1 column, and I wrote each values separated as comma. However, it fails to be treated like a regular csv when I open it in editor, and there are issues when I am importing it in R through read.table

    forloop{

    row <- paste0("",row,",",value)

    }

    dataframe[i,] <- substring(row.temp,2)

2.I created a data frame that has missing values NA for values that are not present like,

t  NA w e NA
NA NA t q NA

And then I write to csv as

write.table(dataframe,file = "test.csv", row.names = FALSE , col.names = FALSE, na = "", quote = FALSE, sep = ",")

But, I have unnecessary , for NA values

  1. Pushing each row to a vector and writing to csv each row by row.

    forloop{

    row.temp <- c(row.temp,values)

    } write.table(temp,file = "test.csv", row.names = FALSE , col.names = FALSE, append=TRUE, sep = ",")

But, the problem is each vector value is written to each new line.

I want to create this CSV file with the format through R. What approach could I take to solve this. I'm sure many people must have faced this issue. Thanks!!

Upvotes: 1

Views: 2138

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521209

Have you tried using cat? Just write the data you want directly to the output file line by line.

fileOut <- file("output.txt")
apply(dataframe, 1, function(x) {
                       l <- paste0(x[!is.na(x)], collapse=",")
                       cat(l, file=fileOut, append=TRUE, sep = "\n")

                    })

Note that I have append mode set to TRUE, to ensure that you don't overwrite the previous line during each iteration of apply.

This solution assumes that the data frame dataframe has, as you described in one of your attempts above, NA values in all columns which are missing values. In this case, my snippet removes these NA values before writing to file.

Upvotes: 3

Related Questions