【发布时间】:2014-06-05 11:02:32
【问题描述】:
我正在尝试从数据框中随机抽取两个子样本,提取子样本中列的均值并计算均值之间的差异。据我所知,do.call 中 replicate 的以下功能和使用应该可以正常工作,但我不断收到错误消息:
示例数据:
> dput(a)
structure(list(index = 1:30, val = c(14L, 22L, 1L, 25L, 3L, 34L,
35L, 36L, 24L, 35L, 33L, 31L, 30L, 30L, 29L, 28L, 26L, 12L, 41L,
36L, 32L, 37L, 56L, 34L, 23L, 24L, 28L, 22L, 10L, 19L), id = c(1L,
2L, 2L, 3L, 3L, 4L, 5L, 6L, 7L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 16L, 17L, 18L, 19L, 20L, 21L, 21L, 22L, 23L, 24L,
25L)), .Names = c("index", "val", "id"), class = "data.frame", row.names = c(NA,
-30L))
代码:
# Function to select only one row for each unique id in the data frame,
# take 2 randomly drawn subsets of size 40 from this unique dataset,
# calculate means of both subsets and determine the difference between the two means
extractDiff <- function(P){
xA <- ddply(P, .(id), function(x) {x[sample(nrow(x), 1) ,] }) # selects only one row for each id in the data frame
subA <- xA[sample(xA, 10, replace=TRUE), ] # takes a random sample of 40 rows
subB <- xA[sample(xA, 10, replace=TRUE), ] # takes a second random sample of 40 rows
meanA <- mean(subA$val)
meanB <- mean(subB$val)
diff <- abs(meanA-meanB)
outdf <- c(mA = meanA, mB= meanB, diffAB = diff)
return(outdf)
}
# To repeat the random selections and mean comparison X number of times...
fin <- do.call(rbind, replicate(10, extractDiff(a), simplify=FALSE))
错误信息:
Error in xj[i] : invalid subscript type 'list'
我认为该错误与未以可以提供给rbind 的格式返回函数输出有关,但我尝试的任何方法似乎都不起作用(即我尝试将 outdf 对象转换为数据框和矩阵,仍然得到错误消息)。
我仍在学习 R,因此将不胜感激。谢谢!
【问题讨论】:
-
ddply中的匿名函数缺少返回值。 -
@Roland:我不确定我明白你的意思吗?我将
ddply()函数的结果称为“xA”并将其提供给下一个命令。当然这应该有效吗?我已经以这种方式在循环中尝试了 ddply 函数,它工作正常吗?请你给我一个如何更改代码的例子吗?非常感谢。 -
应该是
xA <- ddply(P, .(id), function(x) {x[sample(nrow(x), 1) ,] })。抱歉,我无法提供更多帮助,但您的代码不是 reproducible。 -
@罗兰。抱歉,我现在在问题中添加了一些可重现的数据。我尝试删除
y <-,但仍然收到相同的错误消息。谢天谢地,我们将收到任何进一步的建议。谢谢
标签: r sample replicate statistics-bootstrap