使用多个变量的函数循环

时间:2015-12-04 23:30:44

标签: r loops apply

以下是df:

的示例
test <- data.frame(employee = rep(c("John", "Brent", "Mike", "Sophia", "Michelle"), 20),
               location = rep(c("home", "away"), 50),
               weekday = sample(1:5, 100, replace = TRUE),
               time1 = sample(20:40, 100, replace = TRUE),
               time2 = sample(10:30, 100, replace = TRUE))

对于&#34;员工&#34;,&#34;位置&#34;和&#34;工作日&#34;的每个独特组合,我想在两次运行一个功能变量如下例所示(我的真实函数要复杂得多):

function(time1, time2) {
  sum(time1) - sum(time2) * mean(time)
}

此外,我希望将结果在单个数据框中返回到类似的内容中(在我的实际问题中,不是每个&#34;员工&#34;将会在每个&#34;平日&#34):

   weekday location employee function_output
1        1     away    Brent                
2        2     away    Brent                
3        3     away    Brent                
4        4     away    Brent                
5        5     away    Brent                
6        1     home    Brent                
7        2     home    Brent                
8        3     home    Brent                
9        4     home    Brent                
10       5     home    Brent                
11       1     away     John                
12       2     away     John                
13       3     away     John                
14       4     away     John                
15       5     away     John                
16       1     home     John                
17       2     home     John                
18       4     home     John                
19       5     home     John                
20       1     away Michelle                
21       2     away Michelle                
22       3     away Michelle                
23       5     away Michelle                
24       1     home Michelle                
25       2     home Michelle                
26       3     home Michelle                
27       4     home Michelle                
28       5     home Michelle                
29       1     away     Mike                
30       2     away     Mike                
31       3     away     Mike                
32       4     away     Mike                
33       5     away     Mike                
34       1     home     Mike                
35       3     home     Mike                
36       4     home     Mike                
37       5     home     Mike                
38       1     away   Sophia                
39       4     away   Sophia                
40       5     away   Sophia                
41       1     home   Sophia                
42       2     home   Sophia                
43       3     home   Sophia                
44       4     home   Sophia                
45       5     home   Sophia 

如果我只有一个变量,我可以使用apply,但我无法弄清楚如何使用多个变量作为子集。

提前致谢。

0 个答案:

没有答案