append dataframes of different size in same csv file (R)

627 Views Asked by At

Wasn't able to find a solution to this. I have a bunch of dataframes (subsets of bigger dataframes), like that.

a     b    c
3,4  good  HJJR

and

cod      x   c     utc    country
jhh34s   5  HJJR    +1     Poland
jhh22d   0  JJHE    +1     Poland

And I would simply like to sink them in a single csv file like so:

a     b    c
3,4  good  HJJR

cod      x   c     utc    country
jhh34s   5  HJJR    +1     Poland
jhh22d   0  JJHE    +1     Poland

Is this even possible? It's important to end up with a csv file though. And obviously the dfs have different number of rows and columns. Thank you

1

There are 1 best solutions below

0
On BEST ANSWER

There isn't really an easy way to do exactly what you want. But one hacky way is to use the sink() function to redirect all console output to a file.

df1 <- data.frame( A= c(1,2,3,4), B= c("a", "b", "c", "d"))
df2 <- data.frame( A= c(1,2,3))

# start redirecting output
sink(file = "file1.csv")
df1
df2
# close the file
sink()

This of course will not give you a native csv, but you could then open and write the file again.

file2 <- read.table(file = "file1.csv", sep = " ", fill = TRUE)
write.csv(file2 ,file= "file2.csv")