在函数中获取并处理 ddply 中的整行
在 ddply 中抓取一个或多个进行处理很容易,但是有没有办法抓取整个当前行并将其传递给函数?或者获取运行时确定的一组列?
让我举例说明:
给定一个像这样的数据框,
df = data.frame(a=seq(1,20), b=seq(1,5), c= seq(5,1))
df
a b c
1 1 1 5
2 2 2 4
3 3 3 3
我可以编写一个函数来对数据框的一行中的命名列进行求和,如下所示:
selectiveSummer = function(row,colsToSum) {
return(sum(row[,colsToSum]))
}
当我为这样的行调用它时,它会起作用:
> selectiveSummer(df[1,],c('a','c'))
[1] 6
所以我想将其包装在匿名中函数并在 ddply 中使用它来将其应用到表中的每一行,类似于下面的示例,
f = function(x) { selectiveSummer(x,c('a','c')) }
#this doesn't work!
ddply(df,.(a,b,c), transform, foo=f(row))
我想找到一个解决方案,其中可以在运行时确定要操作的列集,所以如果有某种方法可以直接进行 splat从 ddply 的 args 中获取它并将其传递给一个接受任意数量的 args 的函数,这也有效。
编辑:要明确的是,真正的应用程序驱动这不是总和,但这是一个更简单的解释
It's easy to grab one or more in ddply to process, but is there a way to grab the entire current row and pass that onto a function? Or to grab a set of columns determined at runtime?
Let me illustrate:
Given a dataframe like
df = data.frame(a=seq(1,20), b=seq(1,5), c= seq(5,1))
df
a b c
1 1 1 5
2 2 2 4
3 3 3 3
I could write a function to sum named columns along a row of a data frame like this:
selectiveSummer = function(row,colsToSum) {
return(sum(row[,colsToSum]))
}
It works when I call it for a row like this:
> selectiveSummer(df[1,],c('a','c'))
[1] 6
So I'd like to wrap that in an anonymous function and use it in ddply to apply it to every row in the table, something like the example below
f = function(x) { selectiveSummer(x,c('a','c')) }
#this doesn't work!
ddply(df,.(a,b,c), transform, foo=f(row))
I'd like to find a solution where the set of columns to manipulate can be determined at runtime, so if there's some way just to splat that from ddply's args and pass it into a function that takes any number of args, that works too.
Edit: To be clear, the real application driving this isn't sum, but this was an easier explanation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可以使用一个或多个变量以一种唯一的方式标识行,则只能使用 ddply 选择单行。如果存在相同的行,即使您使用所有列,ddply 也会循环遍历多行的数据帧(例如 ddply(df, name(df), f)。
为什么不使用 apply 来代替?Apply 会迭代各行
结果:
You can only select single rows with ddply if rows can be identified in a unique way with one or more variables. If there are identical rows ddply will cycle over data frames of multiple rows even if you use all columns (like
ddply(df, names(df), f
).Why not use apply instead? Apply does iterate over individual rows.
result:
简单...
或者
Simple...
OR