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....
我想在R中创建一个函数,它将根据分类变量(一个因子)的级别创建一个数据框的子集。最终,我的函数将操纵这个子集,但我无法使第一部分工作....
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
.
我的数据框,这里名为Source将始终有一个名为Source $ Espece的变量,另一个名为Source $ Arbre。
Thanks.
谢谢。
2 个解决方案
#1
1
You need to omit "
s in the function. But you need to add "
s to the function call.
你需要省略函数中的“s”。但是你需要在函数调用中添加“s”。
Creation.PLL <- function(Esp, Arb, Source){
Source[Source$Espece == Esp & Source$Arbre == Arb, ]
}
Creation.PLL("SAB", "Vivant", Petite13.b)
#2
0
You can also use substitute
with deparse
if you don't want quoted arguments.
如果不需要带引号的参数,也可以使用deparse替换。
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
#1
1
You need to omit "
s in the function. But you need to add "
s to the function call.
你需要省略函数中的“s”。但是你需要在函数调用中添加“s”。
Creation.PLL <- function(Esp, Arb, Source){
Source[Source$Espece == Esp & Source$Arbre == Arb, ]
}
Creation.PLL("SAB", "Vivant", Petite13.b)
#2
0
You can also use substitute
with deparse
if you don't want quoted arguments.
如果不需要带引号的参数,也可以使用deparse替换。
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