Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

Define leading counter for sequence in R

I am trying to create a numerical sequence in R that looks like this:

ID|class|counter
 A|   z|    1
 A|   z|    2
 A|   c|    1
 A|   c|    2
 A|   z|    3
 B|   z|    1
 B|   c|    1
 B|   c|    2

So the Id is unique and I want to know which order each observation is in given their class. I am trying to count the inner class-Id combination. How does one do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

Here is an option

library(dplyr)    
df1 %>% 
   group_by(ID, class) %>%
   mutate(counter = row_number())

-output

# A tibble: 8 x 3
# Groups:   ID, class [4]
#  ID    class counter
#  <chr> <chr>   <int>
#1 A     z           1
#2 A     z           2
#3 A     c           1
#4 A     c           2
#5 A     z           3
#6 B     z           1
#7 B     c           1
#8 B     c           2

Or with data.table

setDT(df1)[, counter := rowid(ID, class)]

data

df1 <- structure(list(ID = c("A", "A", "A", "A", "A", "B", "B", "B"), 
    class = c("z", "z", "c", "c", "z", "z", "c", "c"), counter = c(1L, 
    2L, 1L, 2L, 3L, 1L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...