1

I have a following dataframe in r

  names       values
   abc          34
   def          12,23
   rty          34,67,89

My desired dataframe would be

   names       values
   abc          34
   def_1        12
   def_2        23
   rty_1        34
   rty_2        67
   rty_3        89 

I am able to separate the values in different rows but how can I alter the names column as desired

   splitdat <- do.call("rbind", strsplit(df$values[3], ","))
   splitdat <- data.frame(apply(splitdat, 2, as.numeric))
   colnames(splitdat)[1] <- "column1" 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Neil
  • 7,937
  • 22
  • 87
  • 145
  • Very close to a duplicate of https://stackoverflow.com/questions/13773770/split-comma-separated-column-into-separate-rows – thelatemail Sep 21 '17 at 05:44

1 Answers1

3

We can use separate_rows

library(dplyr)
library(tidyr)
separate_rows(df1, values, sep=",") %>%
      mutate(names = make.unique(names, sep="_"))

Or we create a sequence column by group and then paste

separate_rows(df1, values, sep=",") %>% 
       group_by(names) %>%
       mutate(names1 = if(n()>1) paste(names, row_number(), sep="_") else names) %>%
       ungroup() %>%
       select(names1, values) %>% 
       rename(names= names1)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I want only comma seperated to be break up in different rows. above code also breaks cells which are seperated by white spaces. And how can I number `abc_1,abc_2` if it has two comma seperated entries – Neil Sep 21 '17 at 05:21
  • 1
    I got it by `seperate_rows(d1,sep = ",")` – Neil Sep 21 '17 at 05:23
  • How can I achieve rows which are seperated in different rows to be named as `abc_1 ,abc_2` ? – Neil Sep 21 '17 at 05:25
  • How can we achieve the desired column `names` ? – Neil Sep 21 '17 at 06:01
  • @Neil Updated the post with `make.unique`. Please let me know if that works. Or else – akrun Sep 21 '17 at 06:26