假設我有回傳串列的函式
fun <- function()
{
return(list(c(1,2,3), c(4,5,6), c(7,8,9)))
}
現在寫作fun()給了我
[[1]]
[1] 1 2 3
[[2]]
[1] 4 5 6
[[3]]
[1] 7 8 9
但是有沒有辦法得到這樣的東西?
list(c(1,2,3),
c(4,5,6),
c(7,8,9))
編輯:我怎樣才能保留一個不錯的輸出和對回傳的串列進行操作的可能性?
uj5u.com熱心網友回復:
我想你可能想要一個美化版的dput:
fun <- function(x) {
text_con <- textConnection("output", "w")
dput(x, text_con)
close(text_con)
formatR::tidy_source(text = output, args.newline = TRUE, width = 40)
}
例如:
mylist <- list(c(1,2,3), c(4,5,6), c(7,8,9))
fun(mylist)
#> list(
#> c(1, 2, 3),
#> c(4, 5, 6),
#> c(7, 8, 9)
#> )
編輯
如果您希望以特定方式列印串列,但同時保留串列的所有功能,則最好使用自己的列印方法創建 S3 類:
special_list <- function(...) structure(list(...), class = "special_list")
as.special_list <- function(x) `class<-`(as.list(x), "special_list")
print.special_list <- function(x) {
text_con <- textConnection("output", "w")
dput(unclass(x), text_con)
close(text_con)
formatR::tidy_source(text = output, args.newline = TRUE, width = 40)
invisible(x)
}
現在你可以創建一個special_list這樣的:
my_list <- special_list(a = c(1, 2, 3), b = letters[1:3])
my_list
#> list(
#> a = c(1, 2, 3),
#> b = c("a", "b", "c")
#> )
它保留了任何其他串列的功能
my_list$a <- 2 * my_list$a
my_list
#> list(
#> a = c(2, 4, 6),
#> b = c("a", "b", "c")
#> )
這只是意味著如果你想以這種方式列印串列,你需要制作一個special_list而不是一個普通的list。如果special_list要從現有串列創建一個,可以執行以下操作:
newlist <- list(a = 1:3)
newlist
#> $a
#> [1] 1 2 3
newlist <- as.special_list(newlist)
newlist
#> list(a = 1:3)
uj5u.com熱心網友回復:
這個函式回傳的正是那個——但我可能誤解了
print_list <- function(x){
cat("list(", paste(x, collapse="\n "), ")", sep="")
}
print_list(fun())
將其添加到您現有的函式中:
fun <- function(){
cat("list(", paste(list(c(1,2,3), c(4,5,6), c(7,8,9)), collapse="\n "), ")", sep="")
}
如評論中所述,您可以(如果不擔心換行符)使用 dput(fun())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367462.html
下一篇:相同數字的Python組串列
