psoares
psoares

Reputation: 4883

Concatenate factors and replace names in R

I'm starting using R but I'm having some problems doing something that would be quite easy with python =P But I'm not ready to give up (yet)

I have a data.frame with several columns. Some are factors, others integers values.
One of the column has these values:

Levels: High Low Neither SI

What I would like to do is to concatenate High and Low into one factor, what I mean is create a new factor called Foreign that will contain the values of High and Low.
But I having quite some difficulties doing this.

I tried:

dataset[Origin == 'High',]$Origin == 'Foreign'

gsub("High", 'Foreign', dataset, fixed = TRUE)

I also tried to played around with grep but without any luke..

I suppose this is easy, but I'm not able to understand how to deal with issue.

Thanks in advance!

Upvotes: 3

Views: 452

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48251

You can check that

levels(dataset$Origin)
[1] "High" "Low" "Neither" "SI"

So all you need is

levels(dataset$Origin)[1:2] <- "Foreign"

Upvotes: 6

Related Questions