将 DataFrame 保存到 R 中的 .txt 文件(换行中的每个值)

Saving a DataFrame to .txt-file in R (every value in new line)

很长一段时间我都在尝试将 Dataframe 保存到一个 txt 文件中,Dadaframe 的每个条目都在一个新行中。 (但并非所有列都应保存)

所以对于我的例子:

A B column not to save
First Second Value
Third Fourth Value

我创建的 .txt 文件应该如下所示:

first
Second
Third
Fourth

我会向您展示我的尝试,但到目前为止我还不知道该怎么做。

提前致谢

我不确定我是否 100% 理解了您要执行的操作,但看起来您正在尝试将数据按行打印到文本文件中。这是使用 tidyverse 的可能解决方案。我不确定你的数据是什么样的,所以这里有一个稍长的 tibble 只是为了表明它正在做我所看到的你的问题。

为示例创建一些数据:

## if you need to install tidyverse
# install.packages("tidyverse")
library(tidyverse)

dat <-
  tibble(
    w = c("First", "Fourth", "Seventh"),
    x = c("Second", "Fifth", "Eighth"),
    y = c("Third", "Sixth", "Ninth"),
    z = c("do", "not", "want")
  )

数据如下所示:

w       x       y       z
First   Second  Third   do  
Fourth  Fifth   Sixth   not 
Seventh Eighth  Ninth   want

这里我们将数据处理成您想要打印的格式。

dat_to_print <-
  dat %>%
  ## whatever columns you do not want printed would go here
  ## you could also select(w,x,y) instead of dropping the unwanted columns
  select(-z) %>%
  rowwise() %>%
  ## whatever columns you want printed would go here... you can also provide it as c(w,x,y)
  pivot_longer(w:y) %>%
  ## pivot longer will come up with two columns: 
  ## the first is 'name' which holds the former name of the variable (i.e. w, x, or y)
  ## the second is 'value' which is what you want to print as I've understood the problem
  ## it doesn't look like you care about the old column names, so we remove it here
  select(-name)

并创建文本文件。

write.table(dat_to_print, 
            file = "C:\your\folder\location\dat.txt", 
            col.names = FALSE, 
            row.names = FALSE, 
            quote = FALSE)

dat.txt 将如下所示:

First               
Second              
Third               
Fourth              
Fifth               
Sixth               
Seventh             
Eighth              
Ninth