Daniel V
Daniel V

Reputation: 1388

Table in dataframe with vector of lists and vector

I'm trying to create a plot of some data similar to the below example:

set.seed(1)
c <- rnorm(3)
df <- as.data.frame(c)
df$a <- strsplit(as.character(c), "1")

This gives the following:

> table(unlist(df$a))

-0.6264538     -0.8356286             0.           0047        0742332             24 83643324222082 
         1              1              1              1              1              1              1 

What I need is to be able to create a 2D mapping, something similar to what I would have thought would have been created with table(unlist(df$a), c) however that command gives the error:

Error in table(unlist(df$a), c) : all arguments must have the same length

The output should be something like (created by hand):

                            c
c                    -0.8356286   2410047 -0.6264538 0742332   0.  83643324222082
  -0.835628612410047          1         1          0       0    0      0
  -0.626453810742332          0         0          1       1    0      0
  0.183643324222082           0         0          0       0    1      1

Upvotes: 1

Views: 32

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

We can repeat the df$c by length of df$a and then use table

table(rep(df$c, lengths(df$a)), unlist(df$a))


#                   -0.6264538 -0.8356286 0. 0047 0742332 24 83643324222082
#-0.835628612410047          0          1  0    1       0  1              0
#-0.626453810742332          1          0  0    0       1  0              0
#0.183643324222082           0          0  1    0       0  0              1

where

lengths(df$a) #gives
#[1] 2 2 3

and then

rep(df$c, lengths(df$a)) #gives

#[1] -0.6264538 -0.6264538  0.1836433  0.1836433 -0.8356286 -0.8356286
#[7] -0.8356286

Upvotes: 1

Related Questions