-1

I have a data frame that looks like this

  df1
  1. AB-CD-XY 
  2. AC-BE-DF-GH

I want to strip from the last hyphen to get something like this:

 1. AB-CD
 2. AC-BE-DF

This is my code

library(stringr)
ifelse(str_count(df1,'-')==3, 
   df_strip<- sub("^([^-]*-[^-]*-[^-]*).*", "\\1",df1),
   df_strip<- sub("^([^-]*-[^-]*).*", "\\1", df1)
   )

At the moment i get the result below which shows that only the else part of my code works. the sub codes works separately on their own but not in the ifelse statement.

1. AB-CD
2. AC-BE
www
  • 38,575
  • 12
  • 48
  • 84
BenT
  • 37
  • 5
  • You can use `sub("-[^-]*$", "", df1[,1])` – akrun Nov 08 '17 at 15:45
  • 1
    Is `df1` a data.frame or a vector? Please see [how to create a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for better ways to include data in your question that can be copy/pasted into R. Also, `ifelse()` is a vectorized function. You should not be doing assignment within the function itself, you should assign the result. – MrFlick Nov 08 '17 at 15:45

1 Answers1

1

Do not use "<-" inside ifelse

df1 <- c('AB-CD-XY', 'AC-BE-DF-GH')
df1_strip <- ifelse(stringr::str_count(df1,'-')==3, 
   sub("^([^-]*-[^-]*-[^-]*).*", "\\1",df1),
   sub("^([^-]*-[^-]*).*", "\\1", df1)
)

df1_strip

[1] "AB-CD"    "AC-BE-DF"

Also note, df1 is not a data frame here.

Ape
  • 1,159
  • 6
  • 11
  • You are welcome. I also refer to MrFlick's comment for ways how you can improve your possible future questions. – Ape Nov 08 '17 at 16:09