如何使用writeList函数将R列表对象复制到Excel,同时保留原始列表对象中的结构和所有名称?

wmomyfyw  于 2024-01-03  发布在  其他
关注(0)|答案(1)|浏览(189)

我正在使用代码行writeClipboard(gsub(" +", "\t", capture.output(print(nested_list, max = 1e6))))将列表对象nested_list复制/粘贴到Excel。当嵌入矩阵列名中没有空格时,代码工作正常,但如果嵌入矩阵列名中有空格,则在粘贴时错误地添加列。我在下图的左侧显示了正确的R studio输出,使用下面图像中间的上述代码行复制/粘贴到Excel时的错误输出,以及下面图像右侧的Excel中的所需输出。我最好保留原始矩阵列名中的空格,第二个最好的情况是用下划线“_"替换那些空格。有什么建议吗?
生成nested_list的代码在这篇文章的底部。
x1c 0d1x的数据
代码:

  1. nested_list <- list(
  2. A = list(
  3. B = list(
  4. C = matrix(1:6,2,3, dimnames = list(NULL,c("Big Bob","Fat Tom","Old Rob"))),
  5. D = matrix(7:8,2,1, dimnames = list(NULL,"Ink"))
  6. ),
  7. E = matrix(9:16,2,4, dimnames = list(NULL,c("Dog","Fat Cat","Rat","Bat")))
  8. ),
  9. F = list(
  10. G = matrix(17:22,2,3, dimnames = list(NULL,c("Sue","Peg","Jen"))),
  11. H = matrix(23:28,2,3, dimnames = list(NULL,c("AAA","BBB","CCC")))
  12. ),
  13. I = matrix(1:4,2,2, dimnames = list(NULL,c("Big Fat","Pig")))
  14. )

字符串

vfhzx4xs

vfhzx4xs1#

你需要
1.首先用一个保证不会出现在名称/值中的字符替换列/行名称中的空格(如果嵌套值包含带空格的文本,则可能还包括值)
1.将capture.output中的空格替换为制表符
1.将掩码字符替换回空格。

  • 注:* 我用一个矩阵来说明为什么值也应该被考虑。

rapply可以帮助您处理嵌套结构,

  1. nested_list <- list(
  2. A = list(
  3. B = list(
  4. C = matrix(1:6,2,3, dimnames = list(NULL,c("Big Bob","Fat Tom","Old Rob"))),
  5. D = matrix(7:8,2,1, dimnames = list(NULL,"Ink"))
  6. ),
  7. E = matrix(9:16,2,4, dimnames = list(NULL,c("Dog","Fat Cat","Rat","Bat")))
  8. ),
  9. F = list(
  10. G = matrix(17:22,2,3, dimnames = list(NULL,c("Sue","Peg","Jen"))),
  11. H = matrix(23:28,2,3, dimnames = list(NULL,c("AAA","BBB","CCC")))
  12. ),
  13. I = matrix(1:4,2,2, dimnames = list(NULL,c("Big Fat","Pig"))),
  14. J = matrix(c("a a", "b b"), 2, 1)
  15. )
  16. mask_names <- function(m, mask = "_") {
  17. if (length(colnames(m)))
  18. colnames(m) <- gsub("\\s", mask, colnames(m))
  19. if (length(rownames(m)))
  20. rownames(m) <- gsub("\\s", mask, rownames(m))
  21. m[] <- gsub("\\s", mask, m)
  22. m
  23. }
  24. mask <- "_"
  25. stopifnot(!grepl(mask, rapply(nested_list, \(x) c(colnames(x), rownames(x), x))))
  26. writeClipboard(
  27. gsub(mask, " ",
  28. gsub("\\s+", "\t",
  29. capture.output(
  30. print(
  31. rapply(nested_list, mask_names,how = "replace", mask = mask)
  32. )
  33. )
  34. )
  35. )
  36. )

字符串
为了使它更加防弹,您需要将相同的逻辑应用于嵌套列表本身的名称(想想nested_list <- c(nested_list, "non syntactic name" = matrix(1:4, 2, 2)),但如果您可以控制插槽名称/不关心Excel中的错误列表名称,则可能没有必要。

展开查看全部

相关问题