sink a data frame to .txt file

2020-04-30 03:23发布

I have a 4-column data frame named as mytable with hundreds of rows. It looks like

id         name                   count        rate
234     uert e@3 erwafrw23 weq    34           2
324     awrt%rw-fref-sfr-32 eq    78           4
329     jiowerfhguy qwhrb         90           8
123     234huib|f|wer fwfqwasgre  54           3

so as it shows, the name has spaces and special characters. so I can't use write.table to save the data.frame. I tried

sink('myfile.txt')
print(mytable,right=F)
sink()

But I met a problem that sometimes the name is so long that the four column can't show together in the same page, i.e. the third or fourth column may run to the next page.

Is there any method can adjust the width of table sinked to .txt file? Or besides sink(), any other code can be used to save a data frame to .txt file? Thanks.

标签: r
2条回答
贪生不怕死
2楼-- · 2020-04-30 04:06

seems like write.table() should be OK. just specify a seperator, like ",", or something else not appearing in your name column:

    my.df <- data.frame(ID=c(234,324,329,123), 
      name = c("uert e@3 erwafrw23 weq"," awrt%rw-fref-sfr-32 eq","jiowerfhguy qwhrb","234huib|f|wer fwfqwasgre"),
      count = c(34,78,90,54), rate = c(2,4,8,3))

    write.table(my.df, file = "my.df.txt", sep = ",", col.names = colnames(my.df))

    # read it back in
    my.df2 <- read.table(file = "my.df.txt",sep = ",", header = TRUE, stringsAsFactors = FALSE) 

    all(my.df == my.df2) 
    TRUE
查看更多
可以哭但决不认输i
3楼-- · 2020-04-30 04:19

You seem confused about the difference between a file and the console output. There is no limitation to the width of lines with write.table, at least not ones you will approach in normal use. You can control the console screen width with options(width=72) and use capture.output(print(mytable)) so the ouput meets whatever unstated width requirements you might have.

查看更多
登录 后发表回答