xander27 xander27 - 3 months ago 25
R Question

Predict using randomForest package in R

How can I use result of randomForrest call in R to predict labels on some unlabled data (e.g. real world input to be classified)?

Code:

train_data = read.csv("train.csv")
input_data = read.csv("input.csv")
result_forest = randomForest(Label ~ ., data=train_data)
labeled_input = result_forest.predict(input_data) # I need something like this


train.csv:

a;b;c;label;
1;1;1;a;
2;2;2;b;
1;2;1;c;


input.csv:

a;b;c;
1;1;1;
2;1;2;


I need to get something like this

a;b;c;label;
1;1;1;a;
2;1;2;b;

Answer

Let me know if this is what you are getting at.

You train your randomforest with your training data:

# Training dataset
train_data <- read.csv("train.csv")
#Train randomForest
forest_model <- randomForest(label ~ ., data=train_data)

Now that the randomforest is trained, you want to give it new data so it can predict what the labels are.

input_data$predictedlabel <- predict(forest_model, newdata=input_data)

The above code adds a new column to your input_data showing the predicted label.