功能超过一个列表 [英] function over more than one list
问题描述
我没有使用那么多函数,但是当我这样做时,我倾向于使用anon函数和某种形式的apply
.但是,我现在试图编写一个对列表中的项目起作用的函数.
I do not use that many functions but when I do I tend to use an anon function and some form of apply
. I now however am trying to write a function that works over items in a list.
有两个列表,每个列表都有许多项(按项,我指的是例如mylist1[1]
).所有项目均为数据框.我想从mylist1
中获取第一个数据帧,并从mylist2
中获取第一个数据帧,并对这些数据帧中的列运行一堆函数.然后取第二个mylist1
项和第二个mylist2
项,依此类推...
There are two lists that each have many items (by item I mean e.g. mylist1[1]
). All items are dataframes. I want to take the first dataframe from mylist1
and the first dataframe from mylist2
and run a bunch of functions over the columns in those dataframes. Then take the 2nd mylist1
item and the 2nd mylist2
item and so on...
下面是我习惯写的那种东西,但是显然在这种情况下有两个列表是行不通的.谁能帮我快速找到我应该如何使用似乎是造成主要问题的sapply
方法以外的方法来解决这个问题.
Below is the sort of thing I am used to writing but clearly does not work in this case with two lists. Can anyone help me out with a fast way to figure out how I should approach this using something other than sapply
method that seems to be causing the main problem.
a <- c(1:10)
b <- c(1:10)
z <- c(rep("x", 5), rep("y", 5))
df <- data.frame(cbind(a, b, z))
mylist1 <- split(df, z)
mylist2 <- split(df, z)
myfunction <- function(x, y)
{
a <- as.data.frame(x[1])
b <- as.data.frame(y[1])
meana <- mean(a[1])
meanb <- mean(b[1])
model <- lm(a[1]~b[1])
return(c(model$coefficients[2], meana, meanb))
}
result <- sapply(mylist1, mylist2, myfunction)
我还只是想过人们认为用z
而不是split
更好地使用subset
吗?
I also just thought do people think it would be better to subset
by z
rather than split
and do the function that way?
推荐答案
您正在确切地描述mapply
的用例.
You are describing exactly the use case for mapply
.
result <- mapply(myfunction,x=mylist,y=mylist2)
不幸的是,您的示例似乎不喜欢传递两个data.frame(x,y的第一个元素都是data.frame,这与x[1]
和y[1]
似乎矛盾).
Unfortunately your example doesn't seem to enjoy being passed two data.frames (x, y 's first elements are both data.frames, which x[1]
and y[1]
would seem to contradict).
这篇关于功能超过一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!