简体   繁体   中英

Output different sized dataframes on one .txt file in R

I have two dataframes of different size that I want to output into a .txt file. I've been using the write.table function but I can only output one on a .txt file.

dataframe1=data.frame(x=c(1:10), y=c(1:10), z=c(1:10))
dataframe2=data.frame(a=c(1:5), b=c(1:5)) 
write.table( C(dataframe1,dataframe2),
             file = "dataframes.txt", 
             append = F,
             sep = ",",
             row.names = F,
             col.names = F,
             na="",
             quote = F)

I'm trying to get them shown as stacked on top of each other but it is not working. Any suggestions?

You have a few problems in your code.

First, C(dataframe1,dataframe2) creates an error because you used a capital C.

Second, c(dataframe1,dataframe2) outputs a list with 5 items. This is NOT a dataframe or a matrix. This will be coerced into a matrix when you save. Any rows with missing data will be filled automatically which you may not want. That would result in in your code outputting:

1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5

The problem here is that you are trying to concatenate two different dataframes that have different numbers of columns. You can either cbind them together as one large table and save it. But beware that any missing row data may be automatically filled in which you don't want (a and b only have 5 rows compared to xyz with 10 rows).

write.table( cbind(dataframe1,dataframe2),
              file = "dataframes.txt", 
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)

Which will output:

x,y,z,a,b
1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
4,4,4,4,4
5,5,5,5,5
6,6,6,1,1
7,7,7,2,2
8,8,8,3,3
9,9,9,4,4
10,10,10,5,5

Or if you really want them on top of each other you can use separate calls and turn on append.

write.table( dataframe1,
              file = "dataframes.txt", 
              append = F,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)
write( "\n Next Dataframe \n", file = "dataframes.txt", append = T)
write.table( dataframe2,
              file = "dataframes.txt", 
              append = T,
              sep = ",",
              row.names = F,
              col.names = T,
              na="",
              quote = F)

Which will output: 
x,y,z
1,1,1
2,2,2
3,3,3
4,4,4
5,5,5
6,6,6
7,7,7
8,8,8
9,9,9
10,10,10

 Next Dataframe 

a,b
1,1
2,2
3,3
4,4
5,5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM