2014-09-26 50 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 
相关问题