I'm trying to write a function called item_pool which takes an arbitrary function, L1F, as a parameter. How would I get L1F to work in dplyr::mutate within the item_pool function? Please see the following.
#Define item_pool function
item_pool <- function(df,
L1F,
w){
x <- w
df %>%
dplyr::mutate(L1_Items = L1F)
}
#Create data frame
df_ul1 <- data.frame(domain = 1:4,
y = c(.25, .25, .25, .25),
z = c(.25, .25, .25, .25))
#Create L1_Items variable based on L1F function
df_ul1_ip <- item_pool(df = df_ul1,
L1F = (function(x,y,z){x*mean(y, z)})(x,y,z),
w = 20)
For context, this is a small snippet of a function which assigns the number of item pool items to write for each domain (or other structures such items per task within domain) based on a set of standards (i.e., minimum number of items per domain, target test length [w], number of forms, item pool/test length ratio, weights, etc.).
CodePudding user response:
There are a few modifications
- If you want to pass the function directly, you only need
function(...){}
, notfunction(...){}(...)
- To take a mean of two variables at each row,
mean(y, z)
will not work. One way to do that is userowMeans
- Move
x <- w
inside theL1F
function call- This is just a style choice
library(dplyr, warn = FALSE)
#Define item_pool function
item_pool <- function(df,
L1F,
w){
df %>%
dplyr::mutate(L1_Items = L1F(x = w, y, z))
}
#Create data frame
df_ul1 <- data.frame(domain = 1:4,
y = c(.25, .25, .25, .25),
z = c(.25, .25, .25, .25))
#Create L1_Items variable based on L1F function
df_ul1_ip <- item_pool(df = df_ul1,
L1F = function(x,y,z){ x * rowMeans(cbind(y, z)) },
w = 20)
df_ul1_ip
#> domain y z L1_Items
#> 1 1 0.25 0.25 5
#> 2 2 0.25 0.25 5
#> 3 3 0.25 0.25 5
#> 4 4 0.25 0.25 5
Created on 2022-09-16 with reprex v2.0.2