Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (50.2k points)

The following is my data-frame:

> require(reshape)

> df <- data.frame(Size=11:13, Letters=c('a|b','b|c','x|y'))

> rownames(df2)=c("Row1", "Row2", "Row3")

       Size Letters

Row1   11     a|b

Row2   12     b|c

Row3   13     x|y

And from that I want to split the 'Letters' column by the delimeter "|" into multiple columns. My desired output should look like this:

      Size Col1 Col2

Row1   11    a    b

Row2   12    b    c

Row3   13    x    y

When I run the following, it doesn't keep the rownames:

df2=with(df, cbind(Size, colsplit(df$Letters, split = "\\|", names = c('Col1', 'Col2'))))

    Size Col1 Col2

1   11    a    b

2   12    b    c

3   13    x    y

1 Answer

0 votes
by (108k points)

You can do the following code:

tidyr::separate(df, Letters, into = c("Col1", "Col2"))

     Size Col1 Col2

Row1   11    a    b

Row2   12    b    c

Row3   13    x    y

or, you can just add some minor change to your original attempt:

cbind(df["Size"], reshape::colsplit(df$Letters, split = "\\|", names = c('Col1', 'Col2')))

Row names are not retained when using with() or colsplit() so there are no row names for cbind() to find.

If you are a beginner and want to know more about R programming then do check out the following R programming tutorial.

Browse Categories

...