[英]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.