Emilie
Emilie

Reputation: 161

Function creation in R: using a factor level as an argument?

I want to create a function in R that will create a subset of a data frame, based on the level of a categorical variable (a factor). Ultimately, my function will manipulate this subset, but I cannot make the first part work....

Here's my code and the result I get when I use the function:

> 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)

My data frame, here named Source will always have a variable called Source$Espece an another one called Source$Arbre.

Thanks.

Upvotes: 0

Views: 231

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99341

You can also use substitute with deparse if you don't want quoted arguments.

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

Upvotes: 0

Sven Hohenstein
Sven Hohenstein

Reputation: 81703

You need to omit "s in the function. But you need to add "s to the function call.

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

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

Upvotes: 1

Related Questions