【发布时间】:2017-06-28 23:00:27
【问题描述】:
如果我有以下代码:
my_func <- function(var1, var2, var3, var4) {
... (side effect included)
}
df <- crossing(
nesting(var1=...,var2=....)
nesting(var3=...,var4=....)
)
将 my_func 应用于 df 的每一行的最优雅的方法是什么? 加上 my_func 不是一个纯函数,它是为了进行一些副作用(IO,plot ...)而设计的
方法一
my_func_wrapper <- function(row) {
my_func(row['var1'], row['var2'], row['var3'], row['var4'])
}
# Vector coercion is a problem, if variables are not the same type.
apply(df, 1, my_func_wrapper)
方法二
df %>%
rowwise() %>%
do(result=invoke(my_func, .)) %>% #If it ends here, I will be pretty happy.
.$result # Relying auto print feature to plot or trigger some side effect
方法三
#This looks pretty good on its own but it does not play well with the pipe %>%
foreach(row=iter(df, by='row')) %do% invoke(my_func, row)
#Method 3.1 (With Pipe)
df %>%
(function(df) foreach(row=iter(df, by='row')) %do% invoke(my_func, row))
#Method 3.2 this does not work
# df %>%
# foreach(row=iter(., by='row')) %do% invoke(my_func, row)
#Method 3.3 this does not work
#I am trying to get this work with purrr's simplified anonymous function, but it does not work.
# df %>%
# as_function(~ foreach(row=iter(., by='row')) %do% invoke(my_func, row))
有没有更好的方法,可以与%>% 一起使用,来做到这一点?
【问题讨论】:
-
不要忘记包含您正在使用的软件包。我还会在您的问题标签中添加这些包名称(我假设
dplyr?也许foreach?)以增加其被回答的机会。