-1
$\begingroup$
column0       c1  c2  c3    new column  
abc|cds|oko  abc cds oko    oko
avd|afd      avd afd        
       |gs           gs     gs
asd          asd            asd  

enter image description here

I am trying to split the Column0 by | pipe operator and making column c3 content as new column, suppose if the c3 column is blank than c2 content to be filled in new column, if suppose c2 and c3 column are blank than c1 content to be filled in column ?? how to achieve this in R code

$\endgroup$
1
  • $\begingroup$ What should the outcome of the column split look like? Should there be one row where column0 is abc, a second where it's cds, a third where it's oko, and so on? Or are you trying to separate column0 into multiple columns? $\endgroup$
    – Dan Hicks
    Jul 4, 2017 at 11:28

1 Answer 1

1
$\begingroup$

Assuming I understood your question correctly, you could use the tidyr and dplyr packages.

library(tidyr)
library(dplyr)

my_df <- data.frame('column0'=c('abc|cds|oko','avd|afd','|gs','asd'),  stringsAsFactors = FALSE)

new_df <- my_df %>%
   # separate column0 into three columns based on the location of the pipe |
   tidyr::separate(column0, c('c1','c2','c3'), sep ='\\|', remove = FALSE, fill="right") %>%
   # make a newcolumn based on values in column0. Take only letters following the last pipe |
   dplyr::mutate(newcolumn=sub(pattern=".*\\|([a-z]*$)", replacement="\\1", column0)) %>%
   # Make the NA's blanks
   dplyr::mutate_each(funs(ifelse(is.na(.),"",.)))      

new_df

  column0       c1    c2    c3   newcolumn
1 abc|cds|oko   abc   cds   oko       oko
2     avd|afd   avd   afd             afd
3         |gs         gs              gs
4         asd   asd                   asd

Although this puts "gs" in c2 instead of c3.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.