I have mydf
data frame below. I want to split any cell that contains comma separated data and put it into rows. I am looking for a data frame similar to y
below. How could i do it efficiently in few steps? Currently i am using cSplit
function on one column at a time.
I tried cSplit(mydf, c("name","new"), ",", direction = "long")
, but that didn`t work
library(splitstackshape)
mydf=data.frame(name = c("AB,BW","x,y,z"), AB = c('A','B'), new=c("1,2,3","4,5,6,7"))
mydf
x=cSplit(mydf, c("name"), ",", direction = "long")
x
y=cSplit(x, c("new"), ",", direction = "long")
y
There are times when a
for
loop is totally fine to work with in R. This is one of those times. Try:Here's a small test using slightly bigger data:
We can use the
separate_rows
function from the tidyr package.If you don't what to use
separate_rows
function more than once, we can further design a function to iteratively apply theseparate_rows
function.The
expand_fun
takes two arguments. The first argument,df
, is the original data frame. The second argument,vars
, is a character string with the columns names we want to expand. Here is an example using the function.