繁体   English   中英

在 R 管道中应用自定义 function

[英]applying custom function in R pipeline

我有类似于下面的数据。 ppt = 参与者编号,正确= ppt 选择是否正确(1 = 正确,0 = 不正确), key_rt是参与者做出选择时的反应时间

data <- data.frame(ppt = rep(c(1, 2, 3), each = 5),
                   correct = c(0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0), 
                   key_rt = runif(15))

我有一个 function 想应用于这些数据。 它需要正确响应的百分比 (Pc)、平均反应时间 (MRT) 和反应时间的方差 (VRT)。

但是,当我将此 function 加载到我的全局环境中,然后尝试通过运行以下代码将其应用于我的数据时,我收到以下错误消息: “EZ 中的错误(Pc,VRT,MRT):object 'Pc'没找到”

df <- data %>%
  group_by(ppt) %>%
  summarise(Pc = mean(correct),
            VRT = var(key_rt[correct==1]),
            MRT = mean(key_rt[correct==1])) %>% 
  mapply(FUN = EZ(Pc, VRT, MRT))

我想知道这是不是因为我用过的管道。 尽管在应用 EZ function 之前计算了 Pc,但似乎 function 无法识别 function 工作所需的此 Pc。

任何建议将不胜感激!

将 output 存储在每个ppt的列表中,并使用unnest_wider获取单独的列。

library(dplyr)
library(tidyr)

data %>%
  group_by(ppt) %>%
  summarise(Pc = mean(correct),
            VRT = var(key_rt[correct==1]),
            MRT = mean(key_rt[correct==1]), 
            out = list(EZ(Pc, VRT, MRT, n()))) %>%
  unnest_wider(out)

#    ppt    Pc    VRT   MRT      v     a     Ter
#  <dbl> <dbl>  <dbl> <dbl>  <dbl> <dbl>   <dbl>
#1     1   0.6 0.0399 0.500  0.407 0.997  0.255 
#2     2   1   0.130  0.391  1.36  1.61  -0.0840
#3     3   0.4 0.282  0.574 -0.249 1.63  -0.0775

我使用n = n()表示组中的行数。 我猜这就是它应该在这里的意思。

使用mutate而不是mapply 您还需要修复参数n的默认值: lenght(correct)不起作用,因为 scope 中没有correct的变量。 我必须在这里猜测,但我认为n = length(Pc)应该可以。

请注意,与 Ronak 的解决方案不同,这将在整个 data.frame 上进行矢量化; that is, the function EZ will be called once in your example, and the arguments will be column vectors of length 3. Whereas in Ronak's example the function will be called three times (once per group), and each time its arguments will be just单个值。 —根据您提供的信息,我不知道这两种解决方案中的哪一种是正确的,在不了解EZ应该计算什么的情况下,两者都是合理的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM