简体   繁体   English

将 R 数据帧输出到 .txt 文件 - 对齐正负值

[英]Outputting an R dataframe to a .txt file - Align positive and negative values

I am trying to output a dataframe in R to a .txt file.我正在尝试将 R 中的数据帧输出到 .txt 文件。 I want the .txt file to ultimately mirror the dataframe output, with columns and rows all aligned.我希望 .txt 文件最终镜像数据帧输出,列和行都对齐。 I found this post on SO which mostly gave me the desired output with the following (now modified) code:我在 SO 上找到了这篇文章,它主要通过以下(现已修改)代码为我提供了所需的输出:

gene_names_only <- select(deseq2_hits_table_df, Gene, L2F)
colnames(gene_names_only) <- c()

capture.output(
  print.data.frame(gene_names_only, row.names=F, col.names=F, print.gap=0, quote=F, right=F),
  file="all_samples_comparison_gene_list.txt"
)

The resultant output, however, does not align negative and positive values.但是,结果输出不会使负值和正值对齐。 See:看:

非对齐值

I ultimately want both positive and negative values to be properly aligned with one another.我最终希望正值和负值彼此正确对齐。 This means that -0.00012 and 4.00046 would have the '-' character from the prior number aligned with the '4' of the next character.这意味着 -0.00012 和 4.00046 会将前一个数字中的“-”字符与下一个字符的“4”对齐。 How could I accomplish this?我怎么能做到这一点?

Two other questions:另外两个问题:

  1. The output file has a blank line at the beginning of the output.输出文件在输出的开头有一个空行。 How can I change this?我怎样才能改变这个?

  2. The output file also seems to put far more spaces between the left column and the right column than I would want.输出文件似乎在左列和右列之间放置的空格比我想要的要多得多。 Is there any way I can change this?有什么办法可以改变这个吗?

Maybe try a finer scale treatment of the printing using sprintf and a different format string for positive and negative numbers, eg:也许尝试使用 sprintf 和不同的正负数格式字符串对打印进行更精细的处理,例如:

> df = data.frame(x=c('PICALM','Luc','SEC22B'),y=c(-2.261085123,-2.235376098,2.227728912))

> sprintf('%15-s%.6f',df$x[1],df$y[1])
[1] "PICALM         -2.261085"

> sprintf('%15-s%.6f',df$x[2],df$y[2])
[1] "Luc            -2.235376"

> sprintf('%15-s%.7f',df$x[3],df$y[3])
[1] "SEC22B         2.2277289"

EDIT: I don't think that write.table or similar functions accept custom format strings, so one option could be to create a data frame of formatted strings and the use write.table or writeLines to write to a file, eg编辑:我不认为 write.table 或类似的函数接受自定义格式字符串,因此一种选择可能是创建格式化字符串的数据框并使用 write.table 或 writeLines 写入文件,例如

dfstr = data.frame(x=sprintf('%15-s', df$x),
                   y=sprintf(paste0('%.', 7-1*(df$y<0),'f'), df$y))

(The format string for y here is essentially what I previously proposed.) Next, write dfstr directly: (这里的y的格式字符串,本质上就是我之前提出的。)接下来直接写dfstr:

write.table(x=dfstr,file='filename.txt',
            quote=F,row.names=F,col.names=F)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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