1

I have the data in this form

Category  Age
A         1.3
A         2.6
A         66.4
A         41.3
A         34.5
B         4.34
B         53.2
B         6.23
B         21.33
B         44.23
C         1.3
C         2.6
C         66.4
C         41.3
C         34.5

I want to store the corresponding values of each category in a separate vector. I've 1800 data points, what would be the fastest way to do that?

1 Answers1

1

A fast option would be split to split it to a list of vectors

lst1 <-  with(df1, split(Age, Category))

If we need to create individual objects (not recommended) with names 'A', 'B', 'C', ...

list2env(lst1, .GlobalEnv)

-check the vectors

A
#[1]  1.3  2.6 66.4 41.3 34.5
B
#[1]  4.34 53.20  6.23 21.33 44.23
C
#[1]  1.3  2.6 66.4 41.3 34.5

data

df1 <- structure(list(Category = c("A", "A", "A", "A", "A", "B", "B", 
"B", "B", "B", "C", "C", "C", "C", "C"), Age = c(1.3, 2.6, 66.4, 
41.3, 34.5, 4.34, 53.2, 6.23, 21.33, 44.23, 1.3, 2.6, 66.4, 41.3, 
34.5)), class = "data.frame", row.names = c(NA, -15L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I did `a<-lst1$a` it has Levels at the end. How do I get rid of levels? – Hamza Mahmood Dec 10 '20 at 23:24
  • @HamzaMahmood You don't need that. as the `list2env` automaticlaly creates the vector with names 'A', 'B' – akrun Dec 10 '20 at 23:25
  • I see, it still has level at the end... – Hamza Mahmood Dec 10 '20 at 23:27
  • @HamzaMahmood if you have factor column, just do `as.character(lst1$a)` – akrun Dec 10 '20 at 23:27
  • @HamzaMahmood Based on the example, I assumed that the first column is `character` and the second `numeric` class. If both are `factors`, you need to convert to `character` and for the `numeric` column it would be `as.numeric(as.character(lst1$a))` – akrun Dec 10 '20 at 23:28