RRR
RRR

Reputation: 133

Convert vector element in tibble to expand

I have the following data set.

The tbl tibble has vector elements in the coef column.

coefs = c(1, 2, 3, 4)
coefs2 = c(2, 3, 4, 5)
names(coefs) = c("a", "b", "c", "d")
names(coefs2) = c("a", "b", "c", "d")
tbl = tibble(coef = list(coefs, coefs2), val=c("n1", "n2"))
tbl

# A tibble: 2 x 2
  coef      val  
  <list>    <chr>
1 <dbl [4]> n1   
2 <dbl [4]> n2   

I want to convert tbl tibble to the following expected_tbl tibble by using pipe operator(like map, mutate and foreach)

Could you tell me how to convert?

expected_tbl = tibble(a = c(1, 2), 
                      b = c(2, 3), 
                      c = c(3, 4), 
                      d = c(4, 5), 
                      val =c("n1", "n2"))

expected_tbl

# A tibble: 2 x 5
      a     b     c     d val  
  <dbl> <dbl> <dbl> <dbl> <chr>
1     1     2     3     4 n1   
2     2     3     4     5 n2 

Upvotes: 1

Views: 278

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389275

With new tidyr you can use unnest_wider

tidyr::unnest_wider(tbl, coef) 

# A tibble: 2 x 5
#      a     b     c     d val  
#  <dbl> <dbl> <dbl> <dbl> <chr>
#1     1     2     3     4 n1   
#2     2     3     4     5 n2   

Upvotes: 4

Cettt
Cettt

Reputation: 11981

you can use bind_rows from the dplyr package:

bind_rows(coefs, coefs2) %>%
  mutate(val = c("n1", "n2"))

# A tibble: 2 x 5
      a     b     c     d val  
  <dbl> <dbl> <dbl> <dbl> <chr>
1     1     2     3     4 n1   
2     2     3     4     5 n2 

Upvotes: 0

Related Questions