[英]R boxplot over summary
從下面的(簡化的)數據中,該數據代表用戶在三個選項之間進行選擇,我想基於值的因素來創建一組框形圖,以顯示用戶選擇值的次數百分比。 所以我要三個框圖,用戶選擇的百分比為0、1和2。
我確定我缺少一些明顯的東西,就像我經常使用R一樣。我可以使用by(dat, dat$user, function(user) {table(user$value)/length(user$value)*100})
,但不知道如何將其轉換為箱線圖。
希望有道理。
user|value
1|2
1|1
1|0
1|2
1|0
2|2
2|2
2|2
2|0
2|2
3|2
3|0
3|1
3|0
3|1
4|2
4|0
4|1
4|0
4|1
5|2
5|0
5|1
5|0
5|1
6|2
6|0
6|0
6|1
6|2
7|0
7|0
7|1
7|0
7|1
8|2
8|2
8|1
8|1
8|2
9|1
9|0
9|0
9|0
9|0
10|1
10|2
10|0
10|2
10|1
我將使用plyr
軟件包創建摘要。 首先,您應該將value
轉換為因數,以便當某些用戶從不選擇某個值時,該值將為0%。
dat$value <- factor(dat$value)
現在,您編寫需要一個數據框的摘要函數(從技術上講,此步驟可以拖入下一步,但這樣更易讀)。
p.by.user <- function(df){
data.frame(prop.table(table(df$value)))
}
然后,將此功能應用於user
定義的dat
每個子集。
dat.summary <- ddply(dat, .(user), p.by.user)
此數據的基本圖形箱圖將按以下方式完成。
with(dat.summary, boxplot(Freq ~ Var1, ylim = c(0,1)))
如果您不介意我的兩分錢,我不知道箱線圖是處理此類數據的正確方法。 這不是非常密集的數據(如果您的樣本是真實的),並且箱線圖無法捕獲決策之間的依賴關系。 即,如果某個用戶頻繁選擇1
超級用戶,則他們必須少選擇另一個超級用戶。
您可以為每個用戶嘗試一個填充的條形圖,如果使用ggplot2
則不需要任何預先匯總。 代碼看起來像這樣
ggplot(dat, aes(factor(user), fill = value)) + geom_bar()
# or, to force the range to be between 0 and 1
# + geom_bar(position = "fill")
您正在尋找類似這樣的東西嗎?
user <- rep(1:10,each=5)
value <- sample(0:2,50,replace=T)
dat <- data.frame(user,value)
percent <- unlist(
by(dat, dat$user,
function(user) {
table(user$value)/length(user$value)*100
}
)
)
# make a vector with all percentages
percent <- unlist(percent)
# extract the necessary info from the names
value <- gsub("\\d+\\.(\\d)","\\1",names(percent))
boxplot(percent~value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.