Question

I would like to use random forest for classification but there are two things that I can't find a solution for: the first one is how can I attach the prediction results to the data frame. Second, how can I get more insights (charts,statistics,etc..) other than a contingency table on the quality of the prediction? Here is my data frame example:

dat <- read.table(text = " TargetVar  Var1    Var2       Var3
 0        0        0         7
 0        0        1         1
 0        1        0         3
 0        1        1         7
 1        0        0         5
 1        0        1         1
 1        1        0         0
 1        1        1         6
 0        0        0         8
 0        0        1         5
 1        1        1         4
 0        0        1         2
 1        0        0         9
 1        1        1         2  ", header = TRUE)

dat$dat$TargetVar <- as.factor(dat$TargetVar) #changed my target variable into a factor
rf <- randomForest(TargetVar~Var1 + Var2+ Var3 ,data=dat,ntree=10,importance=TRUE) #produced the model
table(predict(rf),dat$TargetVar) # got the contingency table

thanks.

Was it helpful?

Solution

I can answer only the first part of your question.

how can I attach the prediction results to the data frame

To do this you can use the cbind function:

Considering the results of your predictions:

predict(rf)

Turn them into a data frame

predResults <- data.frame(predict(rf))

And update your original data frame (dat) to include these results:

dat <- cbind(dat,predResults)

> dat
      TargetVar Var1 Var2 Var3 predict.rf.
  1       0       0    0    7  0.40000000
  2       0       0    1    1  0.69642857
  3       0       1    0    3  1.00000000
  4       0       1    1    7  0.50000000
  5       1       0    0    5  0.30000000
  6       1       0    1    1  0.22380952
  7       1       1    0    0  0.47817460
  8       1       1    1    6  0.52916667
  9       0       0    0    8  0.44444444
  10      0       0    1    5  0.07142857
  11      1       1    1    4  0.66666667
  12      0       0    1    2  1.00000000
  13      1       0    0    9  0.15666667
  14      1       1    1    2  0.51785714
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top