1

First time here hehe. I know that probably my question is a dumb one but I couldn't find the answer with the others questions I've looked into.

I'm trying to convert a string vector (from a larger data frame) which indicates the bands preferences into "1" and "0", being 1 for a specific band and 0 for all others. However, my code is working fine when I use print(), without assigning the results. When I try to use return() or another assignment mode, It comes with an error or only one value. Here is my code:

 for(x in ){ if('Pb&C' %in% x){ print(1)} else{ print(0)} } } 

How can I get the results into a vector?

I've tried these, but all with errors:

for (x in rejeicao) { if ('Pb&C' %in% x) { a <- return(1) } else{ a <- return(0) } } a 

and also:

for (x in rejeicao) { if ('Pb&C' %in% x) { a[x,] <- return(1) } else{ a[x,] <- return(0) } } 

thank you very much

1 Answer 1

3

R is a vectorized language, so you simply need to assign the result of the test to the desired variable.

This code will result in a TRUE/FALSE value.

a <- rejeicao == 'Pb&C' 

To convert to 0/1, we use the fact that TRUE becomes 1 and FALSE becomes 0 when used in a mathematical expression.

a <- (rejeicao == 'Pb&C')*1 

You'll want to learn more about the other keywords you tried using, namely, %in% and return, as I don't think they're doing what you think they are. But StackOverflow is a question/answer site where it's important to ask specific questions and answer them specifically, not a mailing list, so those details aren't appropriate to include here.

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

1 Comment

Using as.numeric(rejeicao) can also be done to convert to 0/1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.