如何在R中将'dput'的输出放在一行中?

7

如何让R中dput的输出在一行中显示?

如何将dput获得的字符串复制到剪贴板中?

3个回答

6

dat <- head(iris) 为例:

  1. dput() 的输出结果压缩成一行并在控制台中显示:
cat(capture.output(dput(dat)), "\n", sep = "")

输出:

structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),     Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4,     1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2,     0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L,     1L), levels = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
  1. 复制到剪贴板(仅适用于Windows):
writeClipboard(paste(capture.output(dput(dat)), collapse = ""))

2
我喜欢这个问题和两个答案。但我想知道在哪种情况下这可能是相关的?非常感谢! - TarJae
4
在提供 Stack Overflow 问题的数据时,将所有内容放在一行中需要较少的垂直空间。 - Julien
2
请注意,仅当“dat”不太大时才有效。 - Julien

4

要直接复制粘贴dput的输出结果,您可以使用read.so包中带有write_clip = T参数的write.so函数:

#devtools::install_github("alistaire47/read.so")
library(read.so)
write.so(head(iris), write_clip = TRUE)

输出

iris <- data.frame(
  Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),
  Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9),
  Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4, 1.7),
  Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.4),
  Species = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")
)

2
嗨Maël!看起来你的回答只回答了OP问题的第二部分(剪贴板部分),但没有回答第一部分(将dput显示在一行中的部分)。 - undefined

-1
dat <- head(iris)为例: dat <- head(iris) 安装包-->"datapasta"
#install.packages(c("datapasta"), dependencies = TRUE) 使用dpasta(注意:仅适用于RStudiodatapasta::dpasta(dat) 输出-->
named list()
> data.frame(
+   Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),
+    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9),
+   Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4, 1.7),
+    Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.4),
+        Species = as.factor(c("setosa","setosa",
+                              "setosa","setosa","setosa","setosa"))
+ )
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa


复制到剪贴板(使用Rstudio)--> datapasta::dmdclip(dat)

1
它不会把所有内容都放在一行上 - undefined
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助他人理解如何解答问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接