【问题标题】:Exporting table as a csv file while preserving correct column numbers将表导出为 csv 文件,同时保留正确的列号
【发布时间】:2016-04-22 20:40:24
【问题描述】:

我将此表作为输出,我想将其保存为csv 文件

value<-cbind(c(rnorm(100,500,90),rnorm(100,800,120)))
genotype<-cbind(c(rep("A",100),rep("B",100)))
gender<-rep(c("M","F","F","F"),50)
df<-cbind(value,genotype,gender)
df<-as.data.frame(df)
colnames(df)<-c("value","genotype","gender")
df$value<-as.numeric(as.character(df$value))
library(Publish)
summary(univariateTable(gender ~ Q(value) + genotype, data=df))

上述命令的输出是这样的:

  Variable        Level   gender = F (n=150)    gender = M (n=50)
1    value median [iqr] 651.4 [499.2, 781.0] 636.8 [539.8, 824.2]
2 genotype            A            75 (50.0)            25 (50.0)
3                     B            75 (50.0)            25 (50.0)
         Total (n=200) p-value
1 644.6 [509.8, 787.5]  0.4859
2           100 (50.0)        
3           100 (50.0)  1.0000

为了将上表导出为.csv 文件,我使用了这段代码

write.csv(summary(univariateTable(gender ~ Q(value) + genotype, data=df)),file="file.csv")

问题在于逗号分隔的四分位数范围的上限值:, 781.0, 824.2, 787.5 最终位于不同的列中,因此第 1 行最终会增加三个额外的列,而表格是不准确。

有什么办法可以避免吗?

【问题讨论】:

  • 你能用write.table之类的东西将它保存为制表符分隔的文件并设置sep = "\t"吗?
  • 我希望.csv 可以方便我的同事操作 MS Excel 访问,所以我不确定这是否适用于 excel。
  • Excel 可以打开制表符分隔的文件,但您不想使用 .csv 扩展名,您可能想做一些类似使用 .txt 的事情。 Excel 可能会询问他们想使用什么作为分隔符(不是最佳的)。您是否也尝试过使用quote=TRUE 选项,我能够创建一个逗号分隔的文件,其中逗号作为其中一列的一部分?
  • @steveb 我测试过,它可以在 LibreOffice 上运行,但 MS Excel 无法打开它。
  • @steveb 很好,quote=TRUE 成功了。现在可以了。谢谢!

标签: r export-to-csv


【解决方案1】:

尝试使用quote=TRUE 选项。 Excel 应该能够区分用于分隔列和部分数据的,

这是带有一个附加选项的命令。

write.csv(
    summary(univariateTable(gender ~ Q(value) + genotype, data=df)),
    file="file.csv", quote = TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多