如何从数据框中选择单个列并将其作为文本文件导出?
以下代码导出完整的数据框:
lapply(names(dat), function(x){write.table(dat[[x]],
file = paste("Output", x, ".txt", row.names=F, col.names=F)))})
答案 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
的第二列写入文件。