菜鳥在這里,我一直在嘗試使用 S3 來總結一個 data.frame 的比例資料,其中有四列字符資料。我的目標是建立一個匯總方法,一次顯示每個變數的每個級別的比例。
我可以看到如何獲得每列的比例
a50survey1 <- table(Student1995$alcohol)
a50survey2 <- table(Student1995$drugs)
a50survey3 <- table(Student1995$smoke)
a50survey4 <- table(Student1995$sport)
prop.table(a50survey1)
prop.table(a50survey1)
Not Once or Twice a week Once a month Once a week More than once a week
0.10 0.32 0.24 0.28 0.06
但是我找不到將所有prop.table輸出組合成一個摘要輸出的方法。除非我真的錯了。我找不到summary.prop.table適合我的 S3 方法。目標是為當前資料框設定,然后在未來放入新的相同大小和觀察資料框。
我真的是一個循序漸進的人,如果你能幫助我,那就太好了 - 謝謝
資料框資訊在這里。有四列,其中每一列都有不同數量的觀察分類選項。
> dput(head(Student1995,5))
structure(list(alcohol = structure(c(3L, 2L, 2L, 2L, 3L), .Label = c("Not",
"Once or Twice a week", "Once a month", "Once a week", "More than once a week"
), class = "factor"), drugs = structure(c(1L, 2L, 1L, 1L, 1L), .Label = c("Not",
"Tried once", "Occasional", "Regular"), class = "factor"), smoke = structure(c(2L,
3L, 1L, 1L, 1L), .Label = c("Not", "Occasional", "Regular"), class = "factor"),
sport = structure(c(2L, 1L, 1L, 2L, 2L), .Label = c("Not regular",
"Regular"), class = "factor")), row.names = c(NA, 5L), class = "data.frame")
匯總資料(如果有幫助) - 編輯
> summary(Student1995)
alcohol drugs smoke sport
Not : 5 Not :36 Not :38 Not regular:13
Once or Twice a week :16 Tried once: 6 Occasional: 5 Regular :37
Once a month :12 Occasional: 7 Regular : 7
Once a week :14 Regular : 1
More than once a week: 3
uj5u.com熱心網友回復:
也許這就是你想要的。每個類別中的值總和為 100%。
lis <- sapply( Student1995, function(x) t( sapply( x, table ) ) )
sapply( lis, function(x) colSums(prop.table(x)) )
$alcohol
Not Once.or.Twice.a.week Once.a.month
0.0 0.6 0.4
Once.a.week More.than.once.a.week
0.0 0.0
$drugs
Not Tried.once Occasional Regular
0.8 0.2 0.0 0.0
$smoke
Not Occasional Regular
0.6 0.2 0.2
$sport
Not.regular Regular
0.4 0.6
和整個總結...
prop.table( table(as.vector( sapply( Student1995, unlist ))) )
Not Not regular Occasional
0.35 0.10 0.05
Once a month Once or Twice a week Regular
0.10 0.15 0.20
Tried once
0.05
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375164.html
