假设我们有一个简单的Excel文件book.xlsx
:
| A | B | C | D | E
1 | Name | Words | | |
2 | Jon | fish | cat | horse | goose
3 | Alex | dog | bird | duck | koala
4 | Bill | dog | cat | goose | deer
5 | George | cat | fish | lizard | duck
下面是我的代码,用于将该文件转换为tsv格式(改编自this answer):
install.packages("rio")
install_formats()
library("rio")
xlsx <- "book.xlsx"
created <- mapply(convert, xlsx, gsub("xlsx", "tsv", xlsx))
这将创建以下tsv文件:
Names Words ..3 ..4 ..5
Jon fish cat horse goose
Alex dog bird duck koala
Bill dog cat goose deer
George cat fish lizard duck
但是我想了解如何做进一步的文件操作,既可以作为转换命令的一部分,也可以作为结果tsv文件的一部分:将Words
列值用逗号分隔,并将{{ 1}}如下删除:
..3 ..4 ..5
关于包/链接或代码示例的任何建议(首选),以说明如何执行上述示例中的文件操作,都是很好的选择。
答案 0 :(得分:0)
在您的问题中有两点令人困惑。它被标记为csv
,但您声明需要使用制表符分隔的文件。另外,不清楚您是否希望将所有word列组合到一个列中。我以为这就是你想要的。
# read file in with readxl package
xlsx <- readxl::read_xlsx("book.xlsx")
# Combine all the word columns into a single column, separated by a comma and a space
xlsx$words2 <- paste(xlsx$Words, xlsx$X__1, xlsx$X__2, xlsx$X__3, sep = ", ")
# select just the name and words column
xlsx <- xlsx[, c("Name", "words2")]
# rename the new column as "Words"
names(xlsx)[2] <- "Words"
# write out, specifying the tab separator
write.table(x = xlsx, file = "out.tsv", row.names = FALSE, sep = "\t")