Sum of returned list: Error: invalid 'type' (list) of argument
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
Bas
Currently graduating for my bachelor bioinformatics. Experience with SQL, Python, C++ and now learning R during my graduation internship.
Updated on December 08, 2020Comments
-
Bas over 3 years
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.
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?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