返回一个列表dplyr mutate() [英] Return a list in dplyr mutate()

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

问题描述

我在我的现实问题中有一个函数,它返回一个列表。有什么办法使用这个与dplyr mutate()?这个玩具示例不工作 - :

  it = data.table(c(a,a, b,b,c),c(1,2,3,4,5),c(2,3,4,2,2))

myfun = function arg1,arg2){

temp1 = arg1 + arg2
temp2 = arg1 - arg2
list(temp1,temp2)

}

myfun(1,2)

it%。%mutate(new = myfun(V2,V3))

我看到它正在循环通过变量的第一个列中的函数输出,但不明白为什么。 p>

谢谢!

解决方案

$ c> data.table 将使用:= (通过引用赋值)运算符。这是一个例证:

  it [,c(paste0(V,4:5)):= myfun V3)] 






如果你真的想要一个列表,为什么不:

  as.list(it [,myfun(V2,V3)])

或者,也许这是你想要的,但是为什么不使用 data.table 功能:

  it [,c(.SD,myfun(V2,V3))] 
#V1 V2 V3 V4 V5
#1:a 1 2 3 -1
#2:a 2 3 5 -1
#3:b 3 4 7 -1
#4:b 4 2 6 2
#5:c 5 2 7 3

注如果 myfun 将其命名为输出,那么这些名称将显示在最终结果列中:

 #V1 V2 V3 new.1 new.2 
#1:a 1 2 3 -1
#2:a 2 3 5 -1
#3 :b 3 4 7 -1
#4:b 4 2 6 2
#5:c 5 2 7 3


I have a function in my real-world problem that returns a list. Is there any way to use this with the dplyr mutate()? This toy example doesn't work -:

it = data.table(c("a","a","b","b","c"),c(1,2,3,4,5), c(2,3,4,2,2))

myfun = function(arg1,arg2) {

temp1 = arg1 + arg2
temp2 = arg1 - arg2
list(temp1,temp2)

}

myfun(1,2)

it%.%mutate(new = myfun(V2,V3))

I see that it is cycling through the output of the function in the first "column" of the new variable, but do not understand why.

Thanks!

解决方案

The idiomatic way to do this using data.table would be to use the := (assignment by reference) operator. Here's an illustration:

it[, c(paste0("V", 4:5)) := myfun(V2, V3)]


If you really want a list, why not:

as.list(it[, myfun(V2, V3)])

Alternatively, maybe this is what you want, but why don't you just use the data.table functionality:

it[, c(.SD, myfun(V2, V3))]
#    V1 V2 V3 V4 V5
# 1:  a  1  2  3 -1
# 2:  a  2  3  5 -1
# 3:  b  3  4  7 -1
# 4:  b  4  2  6  2
# 5:  c  5  2  7  3    

Note that if myfun were to name it's output, then the names would show up in the final result columns:

#    V1 V2 V3 new.1 new.2
# 1:  a  1  2     3    -1
# 2:  a  2  3     5    -1
# 3:  b  3  4     7    -1
# 4:  b  4  2     6     2
# 5:  c  5  2     7     3    

这篇关于返回一个列表dplyr mutate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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