Is there an easy way to do a simple calculation in a list of lists?
x <- list(a=list(1:4),b=list(1:6))
y <- list(a=list(1:4),b=list(1:6))
When I try:
x+y
I receive the error: Error in x + y : non-numeric argument to binary operator
X and y are equal lengths, and contain only integers. With a matrix it is possible to do y+x, is there a way to do this for lists with lists?
combine. lists is an R function developped combine/append two lists, with special attention to dimensions present in both. combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.
Use append() function to add a single element or multiple elements to the vector. A vector in R is a sequence of data elements of the same data type.
The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists. Let's consider a program to add the list elements using the zip function and sum function in Python.
You can use lapply
to go through each 2 lists simultaneously.
lapply(seq_along(x),function(i)
unlist(x[i])+unlist(y[i]))
[[1]]
a1 a2 a3 a4
2 4 6 8
[[2]]
b1 b2 b3 b4 b5 b6
2 4 6 8 10 12
if x and y don't have the same length, you can do this :
lapply(seq_len(min(length(x),length(y)),function(i)
unlist(x[i])+unlist(y[i]))
assuming each list has the same structure, you can use mapply
as follows
mapply(function(x1, y1) x1[[1]]+y1[[1]], x, y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With