1

I've a dataframe,df, in this format:

Variable    X       Y
Var1     1,2,3  .2,.3,.4
Var2     2,3,4  .2,.1,.4
Var3     2,2,1  .1,.2,.4

If I do

df$X[1]

it will give me the following output:

2,3,4

I want to extract each element of this above list. That is, I want to extract 2, then 3 and finally 4.

I want to do this for each Var[i] and X as well Y.

I was trying to do this just for 1 cell:

(df$Var1[1])[1]

So that I get 1 only. But it was giving me "1,2,3".

Cœur
  • 37,241
  • 25
  • 195
  • 267
Beta
  • 1,638
  • 5
  • 33
  • 67

1 Answers1

1

We can use cSplit with melt from data.table

library(splitstackshape)
melt(cSplit(df1, 2:3, ","), measure=patterns("^X", "^Y"), 
       value.name=c("X", "Y"), variable.name="time")[order(Variable)]
#   Variable time X   Y
#1:     Var1    1 1 0.2
#2:     Var1    2 2 0.3
#3:     Var1    3 3 0.4
#4:     Var2    1 2 0.2
#5:     Var2    2 3 0.1
#6:     Var2    3 4 0.4
#7:     Var3    1 2 0.1
#8:     Var3    2 2 0.2
#9:     Var3    3 1 0.4
akrun
  • 874,273
  • 37
  • 540
  • 662