在下面的代码中,我模拟了增加样本大小的掷骰子,并计算了每个样本大小的平均掷骰子。我的 lapply 函数有效,但我对此感到不舒服,因为我知道 sample_n 不是 dplyr 函数并且已被 slice_sample 取代。我想使用 dplyr 解决方案而不是 lapply 中的 sample_n() 使我的代码更好。我想我可能在 lapply 中有其他语法错误。代码如下:
#Dice
dice <- c(1,2,3,4,5,6) #the set of possible outcomes of a dice role
dice_probs <- c(1/6,1/6,1/6) #the probability of each option per roll
dice_df <- data.frame(dice,dice_probs)
#Simulate dice rolls for each of these sample sizes and record the average of the rolls
sample_sizes <- c(10,25,50,100,1000,10000,100000,1000000,100000000) #compute at each sample size
output <- lapply(X=sample_sizes,FUN = function(var){
obs = sample_n(dice_df,var,replace=TRUE)
sample_mean = mean(obs$dice)
new.df <- data.frame(sample_mean,var)
return(new.df)
})
最后一步是计算与预期值 3.5 的差异。我想要一列,显示 3.5 和样本平均值之间的差异。我们应该看到差异随着样本量的增加而减少。
output <- output %>%
mutate(difference = across(sample_mean,~3.5 - .x))
当我运行这个时,它会抛出这个错误:
Error in UseMethod("mutate") :
no applicable method for 'mutate' applied to an object of class "list"
我曾尝试使用 sapply,但出现类似错误:no applicable method for 'mutate' applied to an object of class "c('matrix','array','list')"
如果有帮助,这是我使用 slice_sample 的失败尝试:
output <- lapply(X=sample_sizes,FUN = function(...){
obs = slice_sample(dice_df,...,.preserve=TRUE)
sample_mean = mean(obs$dice)
new.df <- data.frame(sample_mean,...)
return(new.df)
})
我收到此错误:Error: '...' used in an incorrect context