R 如何从函数返回结果和书面语句?

R 如何从函数返回结果和书面语句?,r,function,R,Function,我希望这个函数同时返回结果(数字)和文本 sum_of_squares_cubes <- function(x,y) { sq = x^2 + y^2 cube = x^3 + y^3 return(list(sq, cube)) cat("The sum of squares is", sq, "\n" , "The sum of cubes is", cube, "\n" , ) } 改为修改函数以执行此操作 sum_of_squares_cu

我希望这个函数同时返回结果(数字)和文本

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  return(list(sq, cube))
  cat("The sum of squares is", sq, "\n" ,
      "The sum of cubes is", cube, "\n" ,
      )
}

改为修改函数以执行此操作

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text <- paste("The sum of squares is ", sq, "\n",
                "The sum of cubes is ", cube, "\n", sep = '')
  return(list(sq, cube, text))
}

sum\u of_squares\u cubes修改函数以执行此操作

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text <- paste("The sum of squares is ", sq, "\n",
                "The sum of cubes is ", cube, "\n", sep = '')
  return(list(sq, cube, text))
}

sum\u of_squares\u cubes这些人可能和你一样困惑,你会对他们的建议感到高兴,但要实际返回不同类别的多个项目(这是你要求的),你确实需要一个列表(可能结构复杂)

sum\u of_squares\u cubes sum\u of_squares\u cubes(2,4)
[[1]]
[1] 20
[[2]]
[1] 72
$sqmsg
[1] “平方和为20\n”
$cubemsg
[1] “多维数据集的总和为72\n”

这些人可能和你有同样的困惑,你会对他们的建议感到高兴,但要返回不同类别的多个项目(这是你要求的),你确实需要一个列表(可能结构复杂)

sum\u of_squares\u cubes sum\u of_squares\u cubes(2,4)
[[1]]
[1] 20
[[2]]
[1] 72
$sqmsg
[1] “平方和为20\n”
$cubemsg
[1] “多维数据集的总和为72\n”

以下是一个使用sprintf的更简单解决方案:

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text1 <- sprintf("The sum of squares is %d", sq)
  text2 <- sprintf("and the sum of cubes is %d",  cube)
  return(cat(c("\n", sq, "\n", cube, "\n", text1, "\n", text2)))
}

以下是sprintf的一个更简单的解决方案:

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text1 <- sprintf("The sum of squares is %d", sq)
  text2 <- sprintf("and the sum of cubes is %d",  cube)
  return(cat(c("\n", sq, "\n", cube, "\n", text1, "\n", text2)))
}


return
语句放在
cat
之后
return()之后不执行任何代码。如果要打印,请将
cat()
放在前面。但是,但是,但是<代码>cat
不会“返回”任何内容。我猜OP希望文本输出到控制台,而不是
return
ed。你能澄清一下吗?您希望能够将这些字符串分配给对象,还是只希望在控制台中看到它?@Gregor:任何一种方法都可以。:)将
return
语句放在
cat
之后
return()之后不执行任何代码。如果要打印,请将
cat()
放在前面。但是,但是,但是<代码>cat
不会“返回”任何内容。我猜OP希望文本输出到控制台,而不是
return
ed。你能澄清一下吗?您希望能够将这些字符串分配给对象,还是只希望在控制台中看到它?@Gregor:任何一种方法都可以。:)产量几乎很大。只是最后一部分很奇怪
“平方和为13\n立方体和为35\n”
除非您将其放入某个输出设备,这是该设备的字符向量表示形式。拿着它,
cat
,你会看到函数做了正确的事情。输出几乎很棒。只是最后一部分很奇怪
“平方和为13\n立方体和为35\n”
除非您将其放入某个输出设备,这是该设备的字符向量表示形式。拿着它,然后
cat
,您将看到函数执行正确的操作。这里缺少一些内容。我得到一个错误。这是正确的方法,只是补充说,您永远不应该使用
cat()
返回结果,因为您需要重新运行函数以再次获得结果。大量的
print
方法(和
summary
方法)使用
cat
,然后用户需要使用
capture.output
此处缺少一些内容。我得到一个错误。这是正确的方法,只是补充说,您永远不应该使用
cat()
返回结果,因为您需要重新运行函数以再次获得结果。许多
print
方法(和
summary
方法)使用
cat
,然后用户需要使用
capture.output
 13 
 35 
 The sum of squares is 13 
 and the sum of cubes is 35