繁体   English   中英

R中的函数创建:使用因子水平作为参数?

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

我想在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的变量。

谢谢。

您需要在函数中省略" 。但是您需要在函数调用中添加"

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

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

如果您不想用引号引起来的参数,也可以使用deparse substitute

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM