kgk
kgk

Reputation: 659

Replace characters in a column with numbers R

I have a matrix with last column contains characters:

A
B
B
A
...

I would like to replace A with 1 and B with 2 in R. The expected result should be:

1
2
2
1
...

Upvotes: 2

Views: 15574

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Using factor or a simple lookup table would be much more flexible:

sample_data = c("A", "B", "B", "A")

Recommended:

as.numeric(factor(sample_data))
# [1] 1 2 2 1

Possible alternative:

as.numeric(c("A" = "1", "B" = "2")[sample_data])
# [1] 1 2 2 1

Upvotes: 2

catastrophic-failure
catastrophic-failure

Reputation: 3905

If you are 100% confident only "A" and "B" appear

sample_data = c("A", "B", "B", "A")
sample_data
# [1] "A" "B" "B" "A"
as.numeric(gsub("A", 1, gsub("B", 2, sample_data)))
# [1] 1 2 2 1

Upvotes: 5

Related Questions