我有两个动物园对象 Z1
T1 T2 T3
2013-01-18 20 15 21
2013-01-20 30 18 17
2013-01-21 10 21 24
2013-01-22 15 17 15
2013-01-23 18 16 18
Z2
T1 T2 T3
2013-01-18 0.05 0.01 0.09
2013-01-20 0.02 0.05 0.06
2013-01-21 0.06 0.02 0.07
2013-01-22 0.07 0.06 0.08
2013-01-23 0.01 0.06 0.05
我想把输出作为
T1 T2 T3
2013-01-18 myfunc(20,0.05) myfunc(15,0.01) myfunc(21,0.09)
2013-01-20 myfunc(30,0.02) myfunc(18,0.05) myfunc(17,0.06)
2013-01-21 myfunc(10,0.06) myfunc(21,0.02) myfunc(24,0.07)
2013-01-22 myfunc(15,0.07) myfunc(17,0.06) myfunc(15,0.08)
2013-01-23 myfunc(18,0.01) myfunc(16,0.06) myfunc(18,0.05)
似乎使用apply / rollapply会完成任务,但由于我是R的新手,我无法做到这一点。
更新
假设我也有数据框
Name Quantity Base
T1 100 T3
T2 150 T3
T3 160 T3
输出需要像这样
T1 T2 T3
2013-01-18 myfunc(20,0.05,100) myfunc(20,0.01,150) myfunc(20,0.09,160)
2013-01-20 myfunc(30,0.02,100) myfunc(30,0.05,150) myfunc(30,0.06,160)
2013-01-21 myfunc(10,0.06,100) myfunc(10,0.02,150) myfunc(10,0.07,160)
2013-01-22 myfunc(15,0.07,100) myfunc(15,0.06,150) myfunc(15,0.08,160)
2013-01-23 myfunc(18,0.01,100) myfunc(18,0.06,150) myfunc(18,0.05,160)
请注意,现在第一个参数也基于数据帧的基本列
答案 0 :(得分:3)
你可以尝试
z3 <- z1
z3[] <- mapply(function(x,y,i) myfunc(x[,i], y[,i]),
list(z1), list(z2), seq_len(ncol(z1)))
如果只有一个data.frame(“df1”)并且需要将其传递给myfunc
z3[] <- mapply(function(x,y,z, i) myfunc(x[,i], y[,i], z),
list(z1), list(z2), split(df1$quantity, df1$name),
seq_len(ncol(z1)))