-1

I'm new to this forum so please forgive me possible mistakes. I have a two column data set which looks like this:

enter image description here

I would like to convert the values each id has (in the column "count") into vectors for that id, so f.e. for 274:

vec274 = c(1, 15, 21, 29)

The end goal is using these vectors in a formula.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • 1
    Welcome. Please share your data by editing your post to include the output of ``dput(data)`` rather than posting an image. Images make it hard for people to help you. Thank you. – user438383 Jul 14 '21 at 15:04
  • 1
    [See here](https://stackoverflow.com/q/5963269/5325862) on making a reproducible example that is easier for folks to help with. It's unclear exactly what you want for the output—a list of vectors? a nested data frame? all those vectors loaded into the environment (not a great idea)? – camille Jul 14 '21 at 15:07
  • thank you both! I'll try to change it asap. Ideally, i would like a vector per id, so around ~1200 vectors. I know this is a lot but I need the vectors to add them into a formula and calculate the gini coefficient per id – grace perryman Jul 14 '21 at 15:17
  • I dont see why would you ever want to have individual vectors. I would get a list of vectors, as in @c0bra s answer, and use that list – GuedesBF Jul 14 '21 at 15:44
  • How would I let the function know to use the elements of the list? @GuedesBF Thanks for the input! – grace perryman Jul 14 '21 at 17:14
  • You can use looping functions suited for lists, like `lapply()` and `purrr::map()`. An example: `lapply(list(a=1, b=2, c=3), function(x) x^2)` – GuedesBF Jul 14 '21 at 17:19

3 Answers3

1

You can get a list of your splits by:

split(data$count, data$id)
c0bra
  • 1,031
  • 5
  • 22
1
df <- data.frame(
         vec = c(274L, 274L, 274L, 274L, 56L, 56L, 56L, 56L, 45L, 45L),
       count = c(1L, 15L, 4L, 21L, 4L, 56L, 23L, 21L, 45L, 56L)
      )
df
#>    vec count
#> 1  274     1
#> 2  274    15
#> 3  274     4
#> 4  274    21
#> 5   56     4
#> 6   56    56
#> 7   56    23
#> 8   56    21
#> 9   45    45
#> 10  45    56

#for R Version 4.1.0 onwards
split(df$count, df$vec) |> setNames(paste0('vec', unique(df$vec))) |> list2env(envir = .GlobalEnv)

#for other older version

list2env(split(df$count, paste0('vec', df$vec)), envir = .GlobalEnv)
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
0

We may use group_split

library(dplyr)
data %>%
    select(count, id) %>%
    group_split(id, .keep = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662