我用writeLines试着写了一个, 应该是可以符合你的需求, 你可以再尝试最佳化~
#示范用data frame
library(dplyr)
x <- c('A', 'B', 'C')
y <- c(1, 2, 3)
df <- data.frame(x, y) %>%
mutate_all(as.character)
#先设定一个档案 (档名改word也可以), 等会writeline可以写入
text_print <- file("text_print.txt", open="wt")
ch.col<- names(df)[sapply(df, is.character)]
for (name in ch.col)
{
line1 <- sprintf("Unique value for %s is",name)
line2 <- unique(df[[name]])
writeLines(line1, con = text_print, sep = "\n", useBytes = FALSE)
writeLines(line2, con = text_print, sep = " ", useBytes = FALSE)
writeLines("\n", con = text_print, sep = "\n", useBytes = FALSE)
}
close(text_print)
#开启档案就可以看到写入的资料了