0

I need to export a dataframe from R in CSV format, with some cells having integer(0) values, and other are lists (stored in the dataframe using df$B[k]=list(vector))

A              B                  C
Comp1          integer(0)         c(17, 15)
Comp2          integer(0)         integer(0)                                
Comp3          c(15, 14)          integer(0)  
Comp4          15                 c(12, 13, 14)
Comp5          c(16, 13, 12)      integer(0)

When exported in CSV with fwrite(df, "data.csv"), value of column n is shifted to column n-1 if the value of the cell of the column n-1 is integer(0) .

I tried :

df$B <- as.character(df$B)
df$B[df$B == "integer(0)"] <- "."

But as some cells contain lists, I cannot use as.character and replace "integer(0)" by Something else as it will mess with some cells (list are vectors with ',' in it which will be interpreted as tab when converted with as.character and exported to CSV).

Any way to work around that ?

Ewiwi
  • 3
  • 3
  • 2
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Nov 30 '17 at 14:32

1 Answers1

0

It would have been nice if you had provided us the code from dput(df), like suggested in the question about reproducible examples. Anyway this is how I generated df:

df <- data.frame(A = c("Comp1", "Comp2", "Comp3", "Comp4", "Comp5"))
for(k in 1:5){
  donors <- 16:12
  pick <- list(k1 = 0, k2 = 0, k3 = c(2, 3), k4 = 2, k5 = c(1, 4, 5))
  vector <- donors[pick[[k]]]
  df$B[k] <- list(vector)
}

First thing that come into my mind: is it really necessary to save lists in a data.frame? Second thing: presuambly vector in your example is a vector. But vector is the name of a function implemented in R (see ?vector), so I would give your vector a different name (e.g. vec). To your question: I would not run

df$B <- as.character(df$B)
df$B[df$B == "integer(0)"] <- "."

but

df$B[sapply(df$B, length) == 0] <- NA
fwrite(df, "data.csv", na = ".")
Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • This perfectly solve the issue, thank you very much; I didn't know about the saving option `na='.'`. Also I'll make sure to improve the description of my issues next time. Thanks a lot! – Ewiwi Dec 01 '17 at 09:15
  • You can still update your question. And if you think my answer is useful, you can upvote it in addition to the acceptance. – Qaswed Dec 02 '17 at 14:34