list 返回列表的总和:错误:参数的“类型”(列表)无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34134310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of returned list: Error: invalid 'type' (list) of argument
提问by Bas
For my script I'm returning a bunch of variables in R, and after splitting up my script in more functions I need to return some lists, along with other data.
对于我的脚本,我在 R 中返回了一堆变量,在将脚本拆分为更多函数之后,我需要返回一些列表以及其他数据。
I know I can return multiple values by c(value1, value2)
. But how can I do this when one of the items returned is actually a list?
I'm returning listOne, however it looks like the data type gets changed when returning.
How can I get return the list without changing its type?
我知道我可以通过c(value1, value2)
. 但是,当返回的项目之一实际上是列表时,我该怎么做?我正在返回 listOne,但是看起来返回时数据类型已更改。如何在不更改列表类型的情况下返回列表?
Here's an example:
下面是一个例子:
B <- function(){
listOne <- c(1,2,3,4,5,6)
testString <- "Test"
return(list(listOne, testString))
}
returnlist <- B()
Assigning the variables according to the returned list:
根据返回的列表分配变量:
copy.listOne <- returnlist# [1]
copy.testString <- returnlist[2]
Expected output:
预期输出:
listOne <- c(1,2,3,4,5,6)
print(sum(listOne))
# [1] 21
Actual output:
实际输出:
print(sum(copy.listOne))
Error in print(sum(copy.listOne)) :
error in evaluating the argument 'x' in selecting a method for function 'print': Error in sum(copy.listOne) : invalid 'type' (list) of argument
回答by LyzandeR
When you are working with lists you need to use [[
in order to subset them. In your case when you create the function as follows
当您使用列表时,您需要使用[[
它来对它们进行子集化。在您创建函数时的情况如下
B <- function(){
listOne <- c(1,2,3,4,5,6)
testString <- "Test"
return(list(listOne, testString))
}
returnlist <- B()
you then need to use [[
in order to access the elements of that list.
然后您需要使用[[
以访问该列表的元素。
As you can see below all work now properly:
正如您在下面看到的那样,现在所有工作都正常:
> returnlist[[1]]
[1] 1 2 3 4 5 6
> returnlist[[2]]
[1] "Test"
> sum(returnlist[[1]])
[1] 21