R 读表 <-> 写表

标签 r

在 R 中:

d=read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)

从 d 写回完全相同的文件的命令是什么?

write.table(d, ?)

我给你一个示例输入文件:

one two
1   2

分隔符是“\t”。在使用 read.table 读取后写入完全相同的输出文件的 write.table 参数是什么?

谢谢, 格雷戈尔

最佳答案

问题是您的 read.table 将第 1 列用作 row.names,因此它丢失了列名(“one”)。当你写出来时,你必须做一些特别的事情来取回“一个”的名字。

cbind(one=row.names(d), d) 会将 row.names 添加为名称为“one”的列。然后你只需禁用 row.names 和引号的使用,并指定分隔符:

# Create the test file
filename <- "test.txt"
filename2 <- "test2.txt"
cat("one\ttwo\n1\t2\n", file=filename)

# read it in
d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)

# write it out again
write.table(cbind(one=row.names(d), d), filename2, row.names=FALSE, sep="\t", quote=FALSE)

# Ensure they are the same:
identical(readLines(filename), readLines(filename2)) # TRUE

readLines(filename)
readLines(filename2)

更新 为避免对第一列名称进行硬编码,加载时不得丢失它:

# Read the data without any row.names
d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = NULL)
# Then use the first column as row.names (but keeping the first column!)
row.names(d) <- d[[1]]
d
#  one two
#1   1   2        

# Now you can simply write it out...
write.table(d, filename2, row.names=FALSE, sep="\t", quote=FALSE)

# Ensure they are the same:
identical(readLines(filename), readLines(filename2)) # TRUE

如果您保留第 1 列的名称并像第一个示例中那样使用它,您当然仍然可以删除第 1 列。

关于R 读表 <-> 写表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9036297/

相关文章:

r - 拨浪鼓错误 : the FUN argument to prp is not a function 中的决策树可视化错误

r - 定位输出矩阵的哪些元素

r - R中的分形盒计数

r - 基于并发请求的 RCurl 爬虫问题

将 NA 替换为 NULL

r - 首先按组,然后对于 R data.table 中的每个其他组成员都相同

r - 如何在 R 中下载 .xlsx 文件并将数据加载到数据帧中?

使用 r-markdown 在 HTML 中渲染 LaTeX 表格

r - 在 R/Shiny 中获取用户的当前日期和时间

r - 我想从 R 中的两列中选择两个值中较大的一个