2

Im am trying to split a column of a dataframe into 2 columns using transform and colsplit from reshape package. I don't get what I am doing wrong. Here's an example...

library(reshape)
df1 <- data.frame(col1=c("x-1","y-2","z-3"))

Now I am trying to split the col1 into col1.a and col1.b at the delimiter '-'. the following is my code...

df1 <- transform(df1,col1 = colsplit(col1,split='-',names = c('a','b')))

Now in my RStudio when I do View(df1) I do get to see col1.a and col1.b split the way I want to.

But when I run... df1$col1.a or head(df1$col1.a) I get NULL. Apparently I am not able to make any further operations on these split columns. What exactly is wrong with this?

Brandon Bertelsen
  • 42,225
  • 33
  • 153
  • 250
Gaurav
  • 1,539
  • 1
  • 12
  • 30

1 Answers1

5

colsplit returns a list, the easiest (and idiomatic) way to assign these to multiple columns in the data frame is to use [<-

eg

df1[c('col1.a','col1.b')] <- colsplit(df1$col1,'-',c('a','b'))

it will be much harder to do this within transform (see Assign multiple new variables on LHS in a single line in R)

Community
  • 1
  • 1
mnel
  • 110,110
  • 27
  • 254
  • 248
  • Yes this works for me... I didnt get the list output part... thanks... the df$col1['a'] was what I needed, but your way is better – Gaurav Feb 04 '16 at 05:52