1

In the data frame that I am working on, there is one column of strings that might contains ";". I want to find them and split the string delimited by ";" and copy that row and put the separated string into different rows.

Here is a sample of the data frame:

name     value
a        10
b;c      20
d        30
e        40
f;g;h    50

And this is what I want it to be:

name     value
a        10
b        20
c        20
d        30
e        40
f        50
g        50
h        50

Here is what I was trying to write:

  DF$name <- sapply(DF$name,function(x) {
     if (grepl(";",DF$name)){
     unlist(strsplit(DF$name,"[;]"))}})

The error msg says:

  the condition has length > 1 and only the first element will be used

and I also don't know how to put split string into different rows

Y. Lin
  • 99
  • 2
  • 7

1 Answers1

3
library(dplyr)
library(tidyr)
df%>%mutate(name=strsplit(as.character(name),';'))%>%unnest(name)
  name value
1    a    10
2    b    20
3    c    20
4    d    30
5    e    40
6    f    50
7    g    50
8    h    50
Shenglin Chen
  • 4,504
  • 11
  • 11