功能超过一个列表 [英] function over more than one list

查看:85
本文介绍了功能超过一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用那么多函数,但是当我这样做时,我倾向于使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆