I am struggling to understand the different between the inputs of RF codes on Package 'randomForest'. This reference suggested to use
## S3 method for class 'formula'
randomForest(formula, data=NULL, ..., subset, na.action=na.fail)
## Default S3 method:
randomForest(**x**, **y** =NULL, xtest=NULL, ytest=NULL, ntree=500,
,,,,,,
As I understand, x is the data frame with predictors and y is the response variabel. I see, however, the example of producing this code from the same paper is using the response variable first then the data,
iris.rf <- randomForest(Species ~ ., data=iris, importance=TRUE,
proximity=TRUE)
So, I have wrote my code having both options but I am not sure which one is correct for classification and why?
Here is my code:
I am basically comparing the two codes for rf.
## create data frame
n <- 199
z <- seq(-10, 10, length=n)
x<-sin(x)/x
y <- rnorm(n, 0, 0.1)
xy <- data.frame(x,y)
## create classes
xy$Y<-sample(1:2, n, replace = T)
XY<-xy
n <- nrow(XY)
p <- ncol(XY)-1
colnames(XY)[p+1]<-'Y'
## create trining and test sets
s <- sample(sample(n))
ntr <- round(ptr*n)
id.tr <- s[1:ntr]
id.te <- s[(ntr+1):n]
XY.tr <- XY[id.tr, ]
XY.te <- XY[id.te, ]
y.te <- XY[id.te, p+1]
XY.tr$Y<-as.factor(XY.tr$Y)
##run Random forest
rf1 <- randomForest(XY.tr, data=XY.tr$Y, proximity=TRUE,importance=T)
rf2<-randomForest(formula = XY.tr$Y ~ ., data=XY.tr, proximity = TRUE, importance = T)
Thank you very much for any insight
Both will give you the same answer:
data(iris) #load data
In first approach you explicitly provide the response vector y (but correct your code accordingly):
set.seed(131)
rf1 <- randomForest(y= iris$Species, x=iris[1:4], proximity=TRUE, importance=T)
In second approach you implicitly inform about the response vector y through formula and provide the whole data matrix.
set.seed(131)
rf2<-randomForest(formula = Species ~ ., data=iris, importance=TRUE, proximity=TRUE)
See this R documentation for randomForest :
Argument: x, formula:
a data frame or a matrix of predictors, or a formula describing the model
to be fitted (for the print method, an randomForest object).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.