[英]How to apply specific function over a list in r?
Good morning!早上好!
Suppose i have the following list in r :假设我在 r 中有以下列表:
l=list(c(1,2,30),c(5,5,5))
My question is very simple but I failed to get the right answer !我的问题很简单,但我没有得到正确的答案!
How can i apply a function over rows/columns to get the following outputs :如何在行/列上应用函数以获得以下输出:
l_sum_of_rows=list(33,15)
l_sum_of_columns=list(6,7,35)
Such things are very easy to acheive with matrices .这些事情很容易用矩阵来实现。 However , I don't know how to do same with lists.
但是,我不知道如何处理列表。
Thank you for help in advance !提前感谢您的帮助!
If you think of your data as rows and columns, you should make that list a data.frame.如果您将数据视为行和列,则应将该列表设为 data.frame。 Anyway, the first task is easy with
lapply
:无论如何,使用
lapply
的第一个任务很容易:
sapply(l, sum)
#[1] 33 15
For the second task you can use do.call
if you have a length-two list:对于第二个任务,如果您有一个长度为二的列表,则可以使用
do.call
:
do.call("+", l)
#[1] 6 7 35
For longer lists, you can use Reduce
:对于更长的列表,您可以使用
Reduce
:
Reduce("+", l)
#[1] 6 7 35
Lists of vectors of equal length are (almost) data.frames and there is a lot of specialty functions for those.等长的向量列表(几乎)是 data.frames 并且有很多专门的函数。
l <- list(c(1,2,30),c(5,5,5))
ld <- as.data.frame(l)
rowSums(ld) # sums of rows
colSums(ld) # sums of columns
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.