我想使用随机森林模型来了解社区组装中变量的重要性-我的响应数据是社区矩阵。
library(randomForestSRC)
# simulated species matrix
species
# site species 1 species2 species 3
# 1 1 1 0
# 2 1 0 1
# 3 1 1 1
# 4 1 0 1
# 5 1 0 0
# 6 1 1 0
# 7 1 1 0
# 8 1 0 0
# 9 1 0 0
# 10 1 1 0
# environmental data
data
# site elevation_m PRECIPITATION_mm
# 1 500 28
# 2 140 37
# 3 445 15
# 4 340 45
# 5 448 20
# 6 55 70
# 7 320 18
# 8 200 42
# 9 420 22
# 10 180 8
# adding my species matrix into the environmental data frame
data[["species"]] <-(species)
# running the model
rf_model <- rfsrc(Multivar(species) ~.,data = data, importance = T)
但是我收到一条错误消息:
Error in parseFormula(formula, data, ytry) :
the y-outcome must be either real or a factor.
我猜到问题是存在/不存在的数据,但是我不确定如何克服这个问题。这是功能的限制吗?
答案 0 :(得分:1)
我认为这可能与您构建“数据”数据框的方式有关。使用data[["species"]] <- (species)
时,数据框内有一个数据框。如果您在我刚刚提到的步骤之后str(data)
,则输出如下:
> str(data)
'data.frame': 10 obs. of 4 variables:
$ site : int 1 2 3 4 5 6 7 8 9 10
$ elevation: num 500 140 445 340 448 55 320 200 420 180
$ precip : num 28 37 15 45 20 70 18 42 22 8
$ species :'data.frame': 10 obs. of 4 variables: #2nd data frame
..$ site : int 1 2 3 4 5 6 7 8 9 10
..$ species.1: num 1 1 1 1 1 1 1 1 1 1
..$ species2 : num 1 0 1 0 0 1 1 0 0 1
..$ species.3: num 0 1 1 1 0 0 0 0 0 0
如果您改为将数据框架构建为data2 <- as.data.frame(cbind(data,species))
,然后
rfsrc(Multivar(species.1,species2,species.3)~.,data = data2, importance=T)
似乎可以正常工作,因为我没有收到错误消息,而是得到了一些看起来合理的输出:
Sample size: 10
Number of trees: 1000
Forest terminal node size: 5
Average no. of terminal nodes: 2
No. of variables tried at each split: 2
Total no. of variables: 4
Total no. of responses: 3
User has requested response: species.1
Resampling used to grow trees: swr
Resample size used to grow trees: 10
Analysis: mRF-R
Family: regr+
Splitting rule: mv.mse *random*
Number of random split points: 10
% variance explained: NaN
Error rate: 0
我认为构建所需数据框的方法不是惯用的方法,但我可能是错的。我认为rfsrc()
不知道如何读取嵌套的数据框。我怀疑大多数建模功能是否需要额外的自定义代码。
答案 1 :(得分:0)
下面是一个示例,使用来自vegan
包的示例数据,自动构造一个包含响应中所有物种名称的公式:
library(vegan)
library(randomForestSRC)
data("dune.env")
data("dune")
all <- as.data.frame(cbind(dune,dune.env))
form <- formula(sprintf("Multivar(%s) ~ .",
paste(colnames(dune),collapse=",")))
rfsrc(form, data=all)
假设我们要对2000种进行此操作。这是一个模拟的示例:
nsp <- 2000
nsamp <- 100
nenv <- 10
set.seed(101)
spmat <- matrix(rpois(nsp*nsamp, lambda=5), ncol=nsp,
dimnames=list(NULL,paste0("sp",seq(nsp))))
envmat <- matrix(rnorm(nenv*nsamp), ncol=nenv,
dimnames=list(NULL,paste0("env",seq(nenv))))
all2 <- as.data.frame(cbind(spmat,envmat))
form2 <- formula(sprintf("Multivar(%s) ~ .",
paste(colnames(spmat),collapse=",")))
rfsrc(form2, data=all2)
在这个特定示例中,我们似乎解释了-3%(!!)的方差,但是它不会崩溃,所以这是一件好事...