【发布时间】:2018-10-17 05:23:38
【问题描述】:
我想显示一个函数的许多结果,但我读到你只能返回一个对象,因此如果你想显示更多,就必须使用一个列表。这工作正常,但有时输出不是很可读(在这个假例子中,它并不算太糟糕,但在我的工作中是这样)。如何摆脱或抑制 R 自动添加到我的输出中的这些行/列表位置?
当前输出:
[[1]]
[1] "There are 5 total observations"
[[2]]
[1] "The mean of these observations is 0.564422113896047"
[[3]]
[1] "The observations are shown below:"
[[4]]
[1] 1.0496648 0.4807251 0.8536269 1.7946839 -1.3565901
期望的输出:
"There are 5 total observations"
"The mean of these observations is 0.564422113896047"
"The observations are shown below:"
1.0496648 0.4807251 0.8536269 1.7946839 -1.3565901
我很高兴能够移除每行上方的双括号输出,但保留行号输出。如果我还可以更改各个点的行距,那会更好,但并不是真正需要的。
用于创建此函数/输出的代码:
test <- function(n_observations) {
obs <- rnorm(n_observations)
return(list(
paste0("There are ",n_observations," total observations"),
paste0("The mean of these observations is ",mean(obs)),
paste0("The observations are shown below:"),
obs
))
}
test(n_observations = 5)
编辑: Ronaks 的回答在这种情况下工作得很好,因为我在这个例子中没有包含列表/数据框。我已经更新了下面的函数,以显示您在使用一个礼物时遇到的错误,即;
test <- function(n_observations) {
obs <- rnorm(n_observations)
random_table <- as.data.frame(cbind(c(1:n_observations), obs))
return(cat(
paste0("There are ",n_observations," total observations\n"),
paste("\n"),
paste0("The mean of these observations is ",mean(obs),"\n"),
paste0("The observations are shown below:\n"),
obs,
random_table
))
}
test(n_observations = 5)
输出(和错误):
There are 5 total observations
The mean of these observations is 0.445438123798109
The observations are shown below:
1.677665 1.379066 0.3436419 0.4783038 -1.651487 Error in cat(paste0("There are ", n_observations, " total observations\n"), :
argument 6 (type 'list') cannot be handled by 'cat'
【问题讨论】:
标签: r list function readability