0
> 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

I want to split the Letters column by the delimeter "|" into multiple columns while keeping the rownames, and Size column such that my resulting df looks like:

      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
amwalker
  • 345
  • 1
  • 8
  • 17
  • Try `df[c("col1", "col2")] <- read.table(text = df[["Letters"]], sep = "|")` and then `df[["Letters"]] <- NULL` – markus Mar 31 '20 at 22:30
  • When I ran the first line of code I got this error: Error in textConnection(text, encoding = "UTF-8") : invalid 'text' argument – amwalker Mar 31 '20 at 22:39
  • Nothing [here](https://stackoverflow.com/q/4350440/5325862) works for you? – camille Mar 31 '20 at 23:32
  • @camille, nope :). – amwalker Mar 31 '20 at 23:35
  • This is the same answer as the one accepted https://stackoverflow.com/a/24168383/3962914 you just have to change the arguments according to your data i.e `df %>% separate(Letters, c("Col1", "Col2"), "\\|")` – Ronak Shah Apr 01 '20 at 15:19
  • Actually I tried several answers from other questions and they didn't give the desired outcome, i.e. didn't keep rownames or they separated the columns within the column being separated such that the new "columns" weren't actually "their own" columns. – amwalker Apr 02 '20 at 01:27

1 Answers1

1

You can do:

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

     Size Col1 Col2
Row1   11    a    b
Row2   12    b    c
Row3   13    x    y

or, minor alteration 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.

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56