[英]Formatting output of R dataframe
So i currently have a dataframe in R and I want to export/write it to a text file using write.table()所以我目前在 R 中有一个数据框,我想使用write.table()将它导出/写入文本文件
Here's an example of the dataframe:这是数据框的示例:
ID FirstName LastName Class
1000 John NA C-02
1001 Jane Wellington C-03
1002 Kate NA C-04
1003 Adam West C-05
I want to write it to a text file where for each row, if any column value is NA, then it won't include the word "NA" but proceed to the other column.我想将它写入一个文本文件,其中对于每一行,如果任何列值为 NA,则它不会包含单词“NA”,而是继续到另一列。 The output I want:我想要的输出:
1000 John C-02
1001 Jane Wellington C-03
1002 Kate C-04
1003 Adam West C-05
Example as shown, the first row didn't have a last name entered, so I will proceed to the next column, preventing something like:如图所示,第一行没有输入姓氏,所以我将继续下一列,防止出现类似的情况:
1000 John NA C-02
I did the write.table() command:我做了 write.table() 命令:
write.table(df, "student_list.txt", col.names = FALSE, row.names = FALSE, quote = FALSE, sep="\t")
But the problem is I'm getting the one where NA is included in the second output i mentioned.但问题是我得到的 NA 包含在我提到的第二个输出中。
library(tidyverse)
dta <- tribble(
~ID, ~FirstName, ~LastName, ~Class,
1000, "John", NA, "C-02",
1001, "Jane", "Wellington", "C-03",
1002, "Kate", NA, "C-04",
1003, "Adam", "West", "C-05"
)
dta %>%
unite(column, everything(), sep = " ") %>%
mutate(column = str_remove_all(column, "NA ")) %>%
write.table("student_list.txt", col.names = FALSE, row.names = FALSE, quote = FALSE, sep = "\t")
I would use apply
to remove the NA
s and convert rows into text lines (using paste
), as follows:我将使用apply
删除NA
并将行转换为文本行(使用paste
),如下所示:
data <- apply(df, 1, function(row){
paste(row[!is.na(row)], collapse="\t")
})
write.table(data, "student_list.txt", col.names = FALSE, row.names = FALSE, quote = FALSE, sep="\t")
File output would look like the following:文件输出如下所示:
#1000 John C-02
#1001 Jane Wellington C-03
#1002 Kate C-04
#1003 Adam West C-05
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.