我刚刚开始编写函数和循环,并遇到了一个问题:我试图使用xtabs函数为几个主题ID单独查找频率,但无法解决如何做到这一点。
因此,我有一个dataframe,通常在所有I中都会这样做。
xtabs(~choice+ diff+indicator, data = df)但是,我想对每个ID分别进行分析,然后进行更多的分析(例如,平均选择概率)。
我试图通过分割df来实现它
split_df<-split(df, df$ID)
for (b in seq_along(split_df)) {
print(xtabs(choice + diff+indicator, data = split_df[[b]]))
}理想情况下,我希望有一个包含结果的数据格式列表(每个ID一个),然后使用它进行更多的分析。不过我想不出这点。或者,它可能与一些内置功能,但我不知道其中之一。
谢谢劳拉
发布于 2015-02-19 14:29:42
这是by或lapply的一个很好的用例,而不是for-loop。基本上,结果是相同的,但是没有编写循环、迭代循环和存储适当结果的开销。下面是一个像您这样使用内置mtcars数据集的简单示例:
b <- by(mtcars, mtcars$gear, FUN = function(d) xtabs(~cyl + vs + am, data = d))
l <- lapply(split(mtcars, mtcars$gear), FUN = function(d) xtabs(~cyl + vs + am, data = d))我们可以使用str查看我们创建的内容:
> str(b, 1)
List of 3
$ 3: xtabs [1:3, 1:2, 1] 0 0 12 1 2 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)
$ 4: xtabs [1:2, 1:2, 1:2] 0 0 2 2 0 2 6 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)
$ 5: xtabs [1:3, 1:2, 1] 1 1 2 1 0 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)
- attr(*, "dim")= int 3
- attr(*, "dimnames")=List of 1
- attr(*, "call")= language by.data.frame(data = mtcars, INDICES = mtcars$gear, FUN = function(d) xtabs(~cyl + vs + am, data = d))
- attr(*, "class")= chr "by"
> str(l, 1)
List of 3
$ 3: xtabs [1:3, 1:2, 1] 0 0 12 1 2 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)
$ 4: xtabs [1:2, 1:2, 1:2] 0 0 2 2 0 2 6 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)
$ 5: xtabs [1:3, 1:2, 1] 1 1 2 1 0 0
..- attr(*, "dimnames")=List of 3
..- attr(*, "class")= chr [1:2] "xtabs" "table"
..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d)在这种情况下,我认为lapply的结果可能更接近您的目标,但是(您希望看到)结构非常相似--两者都是xtabs对象的列表。
https://stackoverflow.com/questions/28607975
复制相似问题