简体   繁体   中英

How to conditional concatanate in R?

I'm trying to extract some characters from a vector called "identhog" which is allocated in the table "E". But I want to extract some characters according with its text length. Then if the lenght of the text in the vector is 10 I want to extract some characters, otherwise I want to extract another characters from another position.

if (nchar(E$identhog)==10) {
   E <- mutate(E,prueba2= substr(E$identhog, 2, 6))
   } else {
   E <- mutate(E, prueba2=substr(E$identhog, 3,7))
   } 

I´m using an IF ELSE conditional, but When I run the code the following message shows up.

 "Warning message: In if (nchar(E$identhog) == 10) { : the condition has length > 1 and only 
  the first element will be used"

And R ignores my whole IF conditional and just run:

  E <- mutate(E,prueba2= substr(E$identhog, 2, 6))

How can I fix this? I have investigated about this problem and it seems that happens because I'm attempting to use an if() function to check for some condition, but it's passing a vector to the if() function instead of individual elements.

I understand that R is just checking one element in a vector at one time, but I want to check each individual element. Some users tell that the command "ifelse" is a solution, but it is not working with my data for the amount of information it has.

 ifelse((nchar(E$identhog)==10), 
     E <- mutate(E,prueba2= substr(E$identhog, 2, 6)), 
     E <- mutate(E, prueba2=substr(E$identhog, 3,7)))

Any solution?

You are using ifelse outside mutate , here an example of how to use it with dplyr .

library(dplyr)

df <- data.frame(string = c("1234567890","12345678901"))

df %>% 
  mutate(
    prueba2 = if_else(
      condition = nchar(string) == 10,
      true = substr(string, 2, 6),
      false = substr(string, 3, 7)
      )  
  )
       string prueba2
1  1234567890   23456
2 12345678901   34567

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