我想显示一个函数的许多结果,但已读到只能返回一个对象,因此如果要显示更多内容,则必须使用列表。这可以正常工作,但是有时输出不是很可读(在这个伪造的示例中,它还不错,不过在我的工作中)。如何摆脱或取消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'
答案 0 :(得分:2)
如果您想改善输出输出的方式,可以使用cat
,在每行之后添加“ \ n”以在不同的行中显示输出。
test <- function(n_observations) {
obs <- rnorm(n_observations)
return(cat(
paste0("There are ",n_observations," total observations\n"),
paste0("The mean of these observations is ",mean(obs), "\n"),
paste0("The observations are shown below:\n"),
obs
))
}
test(n_observations = 5)
#There are 5 total observations
# The mean of these observations is -0.785794194405614
# The observations are shown below:
# -0.4806757 -0.6366636 0.3147989 -1.873661 -1.25277
编辑
如果只想显示结果,为什么要return
对其进行处理,则可以从函数本身中打印它们。
test <- function(n_observations) {
obs <- rnorm(n_observations)
random_table <- as.data.frame(cbind(c(1:n_observations), obs))
cat(paste0("There are ",n_observations," total observations\n"),
paste0("The mean of these observations is ",mean(obs), "\n"),
paste0("The observations are shown below:\n"),
obs, "\n\n The table is as below : \n\n")
print(random_table)
}
test(n_observations = 5)
#There are 5 total observations
# The mean of these observations is 0.540141211615552
# The observations are shown below:
# 1.922104 -0.5334201 -0.9881913 1.838563 0.4616504
# The table is as below :
# V1 obs
#1 1 1.9221042
#2 2 -0.5334201
#3 3 -0.9881913
#4 4 1.8385628
#5 5 0.4616504
可以避免最后一个print(random_table)
,而我们只能使用random_table
,但我假设OP对print
还有很多类似的东西,因此在这种情况下很有用。 / p>