Home > Net >  how to group rows by first digit of id column in r
how to group rows by first digit of id column in r

Time:07-28

I have an R dataframe with the numeric id as first column, I would like to group the data frame rows according to the first digit of id

id=c(33211,5966,4478,5589,10003,633,4411,99874,3641) ...

CodePudding user response:

Maybe you want this where you can use substr to extract the first digit of your id like this:

df <- data.frame(id=c(33211,5966,4478,5589,10003,633,4411,99874,3641))

df$new_id <- with(df, as.numeric(substr(id, 1, 1)))
df 
#>      id new_id
#> 1 33211      3
#> 2  5966      5
#> 3  4478      4
#> 4  5589      5
#> 5 10003      1
#> 6   633      6
#> 7  4411      4
#> 8 99874      9
#> 9  3641      3

Created on 2022-07-27 by the reprex package (v2.0.1)

CodePudding user response:

Similar to @Quinten's answer but just arranging the numbers in order

df<-data.frame(id =c(33211,5966,4478,5589,10003,633,4411,99874,3641)) 

df %>%
  mutate(new_id = substr(df$id, 1,1)) %>%
  arrange(by = new_id)
     id new_id
1 10003      1
2 33211      3
3  3641      3
4  4478      4
5  4411      4
6  5966      5
7  5589      5
8   633      6
9 99874      9
  •  Tags:  
  • r
  • Related