Sum all column values ​​in vector

So here is what I'm still trying to understand.

Imagine one like this:

library(tidyverse)
t1 <- tibble(
  id       = c(1,1,1,1,2,2,2,2,2),
  id_sub   = c(1,1,2,2,1,2,2,2,2),
  position = c(1,2,1,2,1,1,2,3,4),
  head     = c(1,1,2,2,1,3,2,2,3)
  )

I want to reach the 5th attribute depend, which has values ​​from headfor each id_sub. This means that each value dependis a vector with a minimum length of 1 (shouldn't be a problem with the tiber, right?).

The result I'm looking for in this example will have an attribute with the following vectors:

c(1,1),c(2,2),c(1),c(3,2,2,3)

Of course, my data is a bit larger, and so far the only solution I could find was to group the smoothing and distribution positionand head:

t1 %>% 
  group_by(id, id_sub) %>% 
  spread(position, head)

This, of course, creates several attributes:

# A tibble: 4 x 6
# Groups:   id, id_sub [4]
     id id_sub   `1`   `2`   `3`   `4`
* <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1      1     1     1    NA    NA
2     1      2     2     2    NA    NA
3     2      1     1    NA    NA    NA
4     2      2     3     2     2     3

position x head , NA. .

m <- t1 %>% 
  filter(id == 2 & id_sub == 2) %>% 
  select(-c(id,id_sub)) %>% 
  spread(position, head) %>% 
  as.matrix()
m <- as.vector(m)
m[!is.na(m)]

:

[1] 3 2 2 3

!

+4
2

:

t1 %>% 
  group_by(data.table::rleid(id_sub)) %>% 
  summarise(hd = list(head)) %>% 
  pull(hd)

:

[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 1

[[4]]
[1] 3 2 2 3
+4

, ?

library(data.table)
split(t1$head, rleid(t1$id_sub))

:

$`1`
[1] 1 1

$`2`
[1] 2 2

$`3`
[1] 1

$`4`
[1] 3 2 2 3
+4

Source: https://habr.com/ru/post/1691099/


All Articles