merging every nth columns from different data frames as text files

Viewed 20

I have three data frames with 50 columns. I would like to write 50 text files in a way that the first text file should contain the first columns from the three data frames, the second text file should contain the second columns from the data frames, and so on. How can I use the column headers, which are the same in the three data frames, as the names of the output text files? Kindly suggest an R solution.

  1. df1 <- data.frame(C1=c(1,2),C2=c(3,4))
  2. df2 <- data.frame(C1=c(5,6),C2=c(7,8))
  3. df3 <- data.frame(C1=c(9,10),C2=c(11,12))
1 Answers

Sample data, a list of three identically-structured frames:

frames <- list(
  frame1 = data.frame(x=1:3, y=4:6, z=7:9),
  frame2 = data.frame(x=11:13, y=14:16, z=17:19),
  frame3 = data.frame(x=21:23, y=24:26, z=27:29))

If instead you have three individual (not list of) frames, create the list with

frames <- list(Df1, Df2, Df3)

Transposing in a fashion:

newframes <- lapply(seq_len(ncol(frames[[1]])), function(i) {
  as.data.frame(lapply(frames, `[[`, i))
})
names(newframes) <- names(frames[[1]])
newframes
# $x
#   frame1 frame2 frame3
# 1      1     11     21
# 2      2     12     22
# 3      3     13     23
# $y
#   frame1 frame2 frame3
# 1      4     14     24
# 2      5     15     25
# 3      6     16     26
# $z
#   frame1 frame2 frame3
# 1      7     17     27
# 2      8     18     28
# 3      9     19     29

Writing to files:

for (nm in names(newframes)) write.csv(newframes[[nm]], paste0(nm, ".csv"))

This implementation makes the column names the name of the original frame, which is less ambiguous (in my opinion) than having them all the same column name x,x,x, y,y,y, etc). If you really need that though (and don't care that R will complain about it if you try to do follow-on work with it), then before writing it,

newframes <- Map(function(nm, x) `colnames<-`(x, rep(nm, ncol(x))), 
                 names(newframes), newframes)
newframes
# $x
#   x  x  x
# 1 1 11 21
# 2 2 12 22
# 3 3 13 23
# $y
#   y  y  y
# 1 4 14 24
# 2 5 15 25
# 3 6 16 26
# $z
#   z  z  z
# 1 7 17 27
# 2 8 18 28
# 3 9 19 29
Related