2013-02-21 79 views
2

我是R的新手,在計算方法之前努力將多個因素組合在一起。這個問題很複雜,因爲我正在對數百個需要分組的因素有不同級別的文件進行這項工作。我從之前的文章中看到如何使用levels()來解決單個級別的這個分組問題,但是我的數據對於這種方法太可變。R:在多個文件中對因素進行分組

基本上,我想計算一個因子的多個水平,然後是一個整體平均值。例如,我想計算Status列中每個物種的平均值:Crypt1,Crypt2,Crypt3,Native,Intro,然後也是Crypt物種的總平均值(包括Crypt1,Crypt2,和Crypt3,但不是Native或Intro)。然而,一個物種要麼具有多級Crypt(變量,直到Crypt8),要麼具有Native和Intro,並且在這些級別中的每個物種的所有物種的最終平均值最終被平均到相同的彙總表中。

例如:

Species Status Value 
A  Crypt1 5 
A  Crypt1 6 
A  Crypt2 4 
A  Crypt2 8 
A  Crypt3 10 
A  Crypt3 50 
B  Native 2 
B  Native 9 
B  Intro  9 
B  Intro  10 

我在想,我可以用每個因素的第一個字母地穴因素的共同作用組,但我很努力的目標的第一個字母,因爲他們的因素,而不是字符串,我不知道如何在它們之間進行轉換。我最終計算使用聚合()的手段,我可​​以得到每個因素的個別手段,但不是分組因素。 任何想法將不勝感激,謝謝!

回答

2

對於個人手段:

# assuming your data is in data.frame = df 
require(plyr) 
df.1 <- ddply(df, .(Species, Status), summarise, ind.m.Value = mean(Value)) 

> df.1 
# Species Status ind.m.Value 
# 1  A Crypt1  5.5 
# 2  A Crypt2  6.0 
# 3  A Crypt3 30.0 
# 4  B Intro  9.5 
# 5  B Native  5.5 

對於整體平均值,這個想法是去除存在於每個條目的Status使用sub/gsub年底的數字。

df.1$Status2 <- gsub("[0-9]+$", "", df.1$Status) 
df.2 <- ddply(df.1, .(Species, Status2), summarise, oall.m.Value = mean(ind.m.Value)) 

> df.2 
# Species Status2 oall.m.Value 
# 1  A Crypt  13.83333 
# 2  B Intro  9.50000 
# 3  B Native  5.50000 

這是你所期待的嗎?

+0

是的,完美的;感謝堆! – user2096647 2013-02-22 21:38:14

0

這是另一種選擇。從概念上講,它與Arun的答案相同,但是它堅持以R爲基礎的函數,並以某種方式保持工作空間和原始數據的整潔。

我假設我們以名爲「temp」的data.frame開始,並且我們要爲個別和分組方式創建兩個新的data.frame s,「T1」和「T2」。我們使用<<-with內的結果分配給全球環境

# Verify that you don't have T1 and T2 in your workspace 
ls(pattern = "T[1|2]") 
# character(0) 

# Use `with` to generate T1 (individual means) 
# and to generate T2 (group means) 
with(temp, { 
    T1 <<- aggregate(Value ~ Species + Status, temp, mean) 
    temp$Status <- gsub("\\d+$", "", Status) 
    T2 <<- aggregate(Value ~ Species + Status, temp, mean) 
}) 

# Now they're there! 
ls(pattern = "T[1|2]") 
# [1] "T1" "T2" 

通知。不是每個人都喜歡使用它,但我認爲在這種情況下可以。這是「T1」和「T2」的樣子。

T1 
# Species Status Value 
# 1  A Crypt1 5.5 
# 2  A Crypt2 6.0 
# 3  A Crypt3 30.0 
# 4  B Intro 9.5 
# 5  B Native 5.5 

T2 
# Species Status Value 
# 1  A Crypt 13.83333 
# 2  B Intro 9.50000 
# 3  B Native 5.50000 

回首with命令,它可能已經好像我們已經改變了「狀態」列的值。但是,這只是在使用with創建的環境中。您的原始data.frame與您開始時的相同。

temp 
# Species Status Value 
# 1  A Crypt1  5 
# 2  A Crypt1  6 
# 3  A Crypt2  4 
# 4  A Crypt2  8 
# 5  A Crypt3 10 
# 6  A Crypt3 50 
# 7  B Native  2 
# 8  B Native  9 
# 9  B Intro  9 
# 10  B Intro 10