R编码 - 导出文件

时间:2015-07-06 17:36:58

标签: r

如何从数据框中选择单个列并将其作为文本文件导出?

以下代码导出完整的数据框:

lapply(names(dat), function(x){write.table(dat[[x]], 
  file = paste("Output", x, ".txt", row.names=F, col.names=F)))})

2 个答案:

答案 0 :(得分:1)

df <- data.frame(x = 1:10,
                 y = letters[1:10],
                 z = rnorm(10))

df
#     x y           z
# 1   1 a  0.36327112
# 2   2 b  1.56697575
# 3   3 c  0.19387687
# 4   4 d  0.58341133
# 5   5 e -0.32764229
# 6   6 f  0.03953639
# 7   7 g  1.45752921
# 8   8 h -0.91446277
# 9   9 i -1.45858541
# 10 10 j -0.25040698

# If I want to export just column y, you could do...
write.table(df["y"], "output.txt")
# You will likely not want the row names...
write.table(df["y"], "output_without_row_names.txt", row.names = FALSE)

答案 1 :(得分:0)

尝试使用

write.table(dat[2],"second_column.dat")

将数据框dat的第二列写入文件。