1
我有一組,看起來像這樣的數據的使用循環重複,選擇從列(數據幀)匹配的行值來創建中的R
species<-"ABC" ind<-rep(1:4,each=24) hour<-rep(seq(0,23,by=1),4) depth<-runif(length(ind),1,50) df<-data.frame(cbind(species,ind,hour,depth)) df$depth<-as.numeric(df$depth)
在本例中,列「ind」具有更多的級別,並且它們的長度並不總是一樣的(這裏每個人都有4級,但實際上有些人擁有數千行數據,而其他只有幾行)。
我想要做的是有一個外部循環或函數,將選擇每個人(「ind」)的所有行,並使用深度/小時列生成boxplot。
這是我心目中的想法,
for (i in 1:length(unique(df$ind))){ data<-df[df$ind==df$ind[i],] individual[i]<-data plot.boxplot<-function(data){ boxplot(depth~hour,dat=data,xlab="Hour of day",ylab="Depth (m)") } } par(mfrow=c(2,2),mar=c(5,4,3,1)) plot.boxplot(individual)
我意識到,這個循環可能是不合適的,但我仍然在學習。我可以一次爲每個人做盒子,但是我希望爲每個人選擇一個更快,更有效的方法來創建或存儲盒子結果。這對於我有更多的人時非常有用(而不是一次一個人......)。提前致謝。
哇!非常感謝,這太棒了!一個簡單的問題。如果我想將每個人的姓名(例如,ind 1,ind 2等)作爲標題,那麼最好的辦法是什麼。我嘗試在boxplot函數中包含main = paste(df $ ind),但沒有給我一個標題... – user1626688
@ user1626688 - 嘗試像這樣替換上面函數中的boxplot行:'boxplot(depth〜hour,data = x,xlab =「Day of day」,ylab =「Depth(m)」,main = paste(「ind =」,x $ ind [1],sep =「」))'你應該很好走。 – thelatemail
太棒了!再次感謝! – user1626688