Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vectors inside dataframe columns in R

I am programming a classificator in R, I have cases that can have multiple classes, so I would like to have both classes in the same row and the column somthing$classes, as a vector. What I mean, is that the column something$classes, of the something data.frame should be like a Java or Python lists of lists. Here is an example of the entering data.frame data:

Case    class    class1     class2
  A       X                    Z
  B                 Y
  C       X         Y          Z
  D                 Y          Z

What I really need to do is to have class, class1 and class2 as one column named classes, with a vector as element, this is the data.frame I would like:

Case    classes  
A       [X, Z] %<- This is a vector, not an string      
B       [Y]          
C       [X, Y, Z]
D       [Y, Z]

Is there a way of having this data.frame structure? If so, how is done and how I could access an individual element inside each classes vector?

Thanks in advance

like image 530
Amnor Avatar asked Dec 08 '25 08:12

Amnor


1 Answers

We can use data.table

library(data.table)
setDT(df1)[, {v1 <- unlist(.SD); list(classes = list(v1[v1!='']))}, Case]
like image 167
akrun Avatar answered Dec 10 '25 22:12

akrun