[英]how to script in R over a factor's levels
我有一個帶有定量變量x和幾個不同因子f1,f2,...,fn的數據框。 在各個因素之間,級別數不是恆定的。
我想按因子水平fi創建x的(單個)密度圖。
我知道如何針對特定因素手工編碼。 例如,這是具有兩個水平的因子的圖。
# set up the background plot
plot(density(frame$x[frame$f1=="level1"]))
# add curves
lines(density(frame$x[frame$f1=="level2"]))
我也可以這樣:
# set up the background plot
plot(NA)
# add curves
lines(density(frame$x[frame$f1=="level1"]))
lines(density(frame$x[frame$f1=="level2"]))
我想知道的是,如果僅將因子指定為輸入,該怎么辦。 我什至不知道如何編寫滿足我需要的for循環,而且我有一種“ R方式”可以避免for循環的感覺。
獎勵:對於繪圖,我想指定軸的極限值。 現在,我以這種方式執行此操作:
xmin=min(frame$x[frame$f1=="level1"],frame$x[frame$f1=="level2"])
如何在腳本中包括這種類型的計算?
我假設您的數據采用格式(稱為df
數據框)
f1 f2 f3 fn value
A........................... value 1
A............................value 2
.............................
B............................value n-1
B............................value n
因此,點陣(或ggplot2)將非常有用。
library(lattice)
densityplot(~value, groups = f1, data = df, plot.points = FALSE)
我認為,這應該使您接近要尋找的東西。
格雷格
您也可以這樣做:
# create an empty plot. You may want to add xlab, ylab etc
# EDIT: also add some appropriate axis limits with xlim and ylim
plot(0, 0, "n", xlim=c(0, 10), ylim=c(0, 2))
levels <- unique(frame$f1)
for (l in levels)
{
lines(density(frame$x[frame$f1==l]))
}
ggplot2
代碼
library(ggplot2)
ggplot(data, aes(value, colour = f1)) +
stat_density(position = "identity")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.