我正在使用包含大學生資料的“調查”資料框。我將學生分為 3 個年齡組 (0-20)、(20-25)、(25 )。
現在我正試圖以圖形方式呈現年齡組和他們的吸煙習慣。
我嘗試了以下腳本
Age_Group <- cut(survey$Age, breaks=c(0, 20, 25, Inf),
labels=c("0-20", "20-25", "25 "))
survey2 <- survey
survey2 <- cbind(survey2, Age_Group)
barplot(table(survey2$Age, survey2$Smoke, legend.text=TRUE, beside=TRUE))
我得到的錯誤是:
Error in table(survey2$Age_Group, survey2$Smoke, legend.text = TRUE, beside = TRUE):
all arguments must have the same length
uj5u.com熱心網友回復:
問題是你在錯誤的地方有一個括號。
barplot(table(survey2$Age, survey2$Smoke, legend.text=TRUE, beside=TRUE))
應該:
barplot(table(survey2$Age, survey2$Smoke), legend.text=TRUE, beside=TRUE)
閱讀表有四列,最后兩列只有一個元素。我想你想要下面。我創建了一個示例資料集來測驗代碼。
survey <- data.frame(Age=(30*rnorm(1000) 45), Smoke=as.numeric(runif(1000) < .2))
Age_Group <- cut(survey$Age, breaks=c(0, 20, 25, Inf), labels=c("0-20", "20-25", "25 "))
survey2 <- survey
survey2 <- cbind(survey2, Age_Group)
barplot(table(survey2$Smoke, survey2$Age_Group), legend.text=TRUE, beside=TRUE)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/536384.html
標籤:r条形图分组
