簡體   English   中英

不同ID的xtabs函數循環

[英]xtabs function loop for different IDs

我剛剛開始編寫函數和循環,並遇到了一個問題:我試圖使用xtabs函數分別查找多個主題ID的頻率,並且無法弄清楚該怎么做。

所以我有一個數據框,通常會在所有ID上做到這一點

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一個),然后對其進行更多分析。 我無法弄清楚。 或者,可能有一些內置功能,但我不知道有一個。

謝謝勞拉

對於bylapply這是一個很好的用例,而不是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對象的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM