0

I would like to convert a charter sequence into a numeric sequence.

My variable is called labCancer and is made like this:

labCancer

[1] M M M M M M M M M M M M M M M M M M M B B B M M M M M M M M M M M M M M M B

I would like to have:

[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0

I tried using

labCancer_2 <- labCancer 

for (i in 1:569)    {
  if (labCancer[i] == "M") {
    labCancer_2[i] <- 1
  } else {

 labCancer_2[i] <- 2

 } }    

but it doesn't work.

Andrea

0

4 Answers 4

1

The only reason I can think of that would cause that loop to not work is failure to initialize labCancer_2. So you would want to do this prior to starting your loop:

labCancer_2 <- numeric(length(labCancer))

If you want to assign to an object element by element in a loop, you need to initialize that object first, or it needs to otherwise exist in some manner.

However, there is a better way to do this that would not require initialization and would be the way many would argue you should do it in R

labCancer_2 <- ifelse(labCancer == "M", 1, 0)

This takes advantage of R's vectorization.

Sign up to request clarification or add additional context in comments.

Comments

0

Depending on what you are using the data for, as long as you only have two values, you can do this:

labCancer_2 <- ifelse(lab_cancer=="M", 1, 0)

If you have multiple values or you want to keep the letters around for reference or graphing, you can make the vector a factor:

labCancer_2 <-factor(lab_cancer, levels=c("B", "M"))

However, the factor begins with 1, so your vector would be 2 2 2 2 ... 1 1 1 ...
rather than
1 1 1 1 ... 0 0 0...

Comments

0

One solution would be to convert your vector to a factor, and then to an integer. This will result in all unique values of your original vector to get a separate integer number:

> x <- c("m", "b", "m", "b")
> x
[1] "m" "b" "m" "b"
> as.factor(x)
[1] m b m b
Levels: b m
> as.integer(as.factor(x))
[1] 2 1 2 1
> c(0, 1)[as.numeric(as.factor(x))]
[1] 1 0 1 0

Using the trick in the last line one can easily change the numbers to match 0 and 1.

Comments

0

create a numeric vector (0,1,0,0,1,1), change it to a vector of characters ("0","1","0","0","1","1")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.