Home > Blockchain >  How Can I Make A Vector of Vectors in R
How Can I Make A Vector of Vectors in R

Time:11-15

I have a simple case where I created a data frame with a group of vectors like this.

df1 = tibble(
  seed = rep(c(289805, 671086, 799837), 4),
  sd = rep(c(1, 3, 5, 10), each=3),
  ar = rep(c(.8, .9, .95), 4)
)
df1

# A tibble: 12 x 3
     #seed    sd    ar
    #<dbl> <dbl> <dbl>
 #1 289805     1  0.8 
 # 2 671086     1  0.9 
 # 3 799837     1  0.95
 # 4 289805     3  0.8 
 # 5 671086     3  0.9 
 # 6 799837     3  0.95
 # 7 289805     5  0.8 
 # 8 671086     5  0.9 
 # 9 799837     5  0.95
 #10 289805    10  0.8 
 #11 671086    10  0.9 
 #12 799837    10  0.95

I want a case where the ar column will be like this

df2 = tibble(
  seed = rep(c(289805, 671086, 799837), 4),
  sd = rep(c(1, 3, 5, 10), each=3),
  ar = rep(c(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), 4)
)
df2

Where I will have something like this.

# A tibble: 12 x 3
     #seed    sd    ar
    #<dbl> <dbl> <dbl>
 #1 289805     1  (0.4, 0.4) 
 # 2 671086     1  (0.45, 0.45) 
 # 3 799837     1  (0.35, 0.6)
 # 4 289805     3  (0.4, 0.4) 
 # 5 671086     3  (0.45, 0.45) 
 # 6 799837     3  (0.35, 0.6)
 # 7 289805     5  (0.4, 0.4) 
 # 8 671086     5  (0.45, 0.45) 
 # 9 799837     5  (0.35, 0.6)
 #10 289805    10  (0.4, 0.4) 
 #11 671086    10  (0.45, 0.45) 
 #12 799837    10  (0.35, 0.6)

Instead I got this error message `Error: Tibble columns must have compatible sizes.

  • Size 12: Existing data.
  • Size 24: Column ar.`

This question is a follow-up question to this answer

CodePudding user response:

Your approach was almost there, simply use a list:

df1$ar <- rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), 4)

df1
     seed sd         ar
1  289805  1   0.4, 0.4
2  671086  1 0.45, 0.45
3  799837  1 0.35, 0.60
4  289805  3   0.4, 0.4
5  671086  3 0.45, 0.45
6  799837  3 0.35, 0.60
7  289805  5   0.4, 0.4
8  671086  5 0.45, 0.45
9  799837  5 0.35, 0.60
10 289805 10   0.4, 0.4
11 671086 10 0.45, 0.45
12 799837 10 0.35, 0.60

EDIT: With tibble:

require(tibble)

df2 = tibble(
  seed = rep(c(289805, 671086, 799837), 4),
  sd = rep(c(1, 3, 5, 10), each=3),
  ar = rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), 4)
)

df2
# A tibble: 12 x 3
     seed    sd ar       
    <dbl> <dbl> <list>   
 1 289805     1 <dbl [2]>
 2 671086     1 <dbl [2]>
 3 799837     1 <dbl [2]>
 4 289805     3 <dbl [2]>
 5 671086     3 <dbl [2]>
 6 799837     3 <dbl [2]>
 7 289805     5 <dbl [2]>
 8 671086     5 <dbl [2]>
 9 799837     5 <dbl [2]>
10 289805    10 <dbl [2]>
11 671086    10 <dbl [2]>
12 799837    10 <dbl [2]>
  • Related