2014-09-26 30 views
0

我想在R中創建一個函數,根據分類變量(一個因子)的級別創建一個數據框的子集。最終,我的功能將操作這個子集,但我不能讓第一部分的工作....在R中創建函數:使用因子級別作爲參數?

這裏是我的代碼,結果我得到的,當我使用的功能:

> Petite13.b [1:5, ] 
    Numero Espece  Arbre Nb 
1  1 BOP Brout_mort 1 
61  1 BOP  Mutile 2 
130  1 SAB  Mutile 1 
213  1 BOP  Vivant 1 
439  1 SAB  Vivant 2 

> Creation.PLL <- function(Esp, Arb, Source){ 
+ x <-Source[Source$Espece== "Esp" & Source$Arbre== "Arb", ] 
+ return(x) 
+ } 
> 
> Creation.PLL(SAB, Vivant, Petite13.b) 
[1] Numero Espece Arbre Nb  
<0 lignes> (ou 'row.names' de longueur nulle) 

我的數據幀,這裏名爲Source將始終有一個名爲Source$Espece的變量,另一個名爲Source$Arbre

謝謝。

+1

你是不是要做'Source [Source $ Espece == Esp&Source $ Arbre == Arb,]'(其中'Esp'和'Arb'沒有引用)? – nrussell 2014-09-26 14:33:30

+0

請發佈一個小的*可重現的*您的數據樣本。 – 2014-09-26 14:35:40

+0

@nrussell即使我把「Esp」放在函數編程和使用它之後,它也不起作用。 – Emilie 2014-09-26 14:39:26

回答

1

您需要在函數中省略" s。但是您需要將" s添加到函數調用中。

Creation.PLL <- function(Esp, Arb, Source){ 
    Source[Source$Espece == Esp & Source$Arbre == Arb, ] 
} 

Creation.PLL("SAB", "Vivant", Petite13.b) 
+0

非常感謝! @Sven Hohenstein – Emilie 2014-09-26 14:56:32

+0

@Emilie不客氣:) – 2014-09-26 14:56:53

0

您還可以使用substitutedeparse如果你不想報價參數。

foo <- function(x, data){ 
    x <- deparse(substitute(x)) 
    data[with(data, Species == x),] 
} 
head(foo(setosa, iris)) 
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
# 1   5.1   3.5   1.4   0.2 setosa 
# 2   4.9   3.0   1.4   0.2 setosa 
# 3   4.7   3.2   1.3   0.2 setosa 
# 4   4.6   3.1   1.5   0.2 setosa 
# 5   5.0   3.6   1.4   0.2 setosa 
# 6   5.4   3.9   1.7   0.4 setosa 
相關問題