简体   繁体   中英

Create a new column based on conditional statement of another column R

I am trying to create a new column that will return Yes or No based on conditions of another column.

I have tried to use grepl , substr and nchar , ifelse . The issue is that the data has characters and numbers in the column that I am trying to condition.

(nchar(as.character(expo$BuyerNumber)) == 3)
(substr(as.character(expo$BuyerNumber),1,1 == 6))  

I want to create aa new column that will have yes or no if the following conditions are met. If the first number starts with 6 and is of length 3 then yes if not then no will be returned.

Examples:

610
610B
620C

All above would return yes

426
62B
21C

All above would return no

One problem, I see, might be that you are comparing substr (which will give a character) to a number. That is likely to give false boolean. Something like below.

(nchar(as.character(expo$BuyerNumber)) == 3)

(as.integer(substr(as.character(expo$BuyerNumber),1,1)) == 6)

If it does not work, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM