Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

Let say, for instance, I have this data frame:

id  name    date

1   Susan   1/1/2020

2   jhon    1/1/2020

3   Susan   1/1/2020

4   eric    2/4/2020

5   eric    2/4/2020

6   Susan   2/1/2020

7   eric    2/4/2020

And I need the following:

id  name    date    output

1   Susan   1/1/2020    1

2   jhon    1/8/2020    1

3   Susan   1/1/2020    2

4   eric    2/4/2020    1

5   eric    2/4/2020    2

6   Susan   2/9/2019    1

7   eric    2/4/2020    3

1 Answer

0 votes
by (108k points)

In R programming you can simply achieve your goal, by the following steps:

The following is data:

# data

tib <- tibble( name = c("susan", "jhon", "susan", "eric", "eric", "susan", "eric"), 

              date = c("1/1/2020", "1/1/2020", "1/1/2020", "2/4/2020", "2/4/2020", "2/1/2020", "2/4/2020"))

The following is the procedure: 

# datawrangle

tib1 <-

  tib %>% 

  group_by(name, date) %>% 

  mutate(output = row_number())

And the result is:

tib1

## # A tibble: 7 x 3

## # Groups:   name, date [4]

##   name  date     output

##   <chr> <chr>     <int>

## 1 susan 1/1/2020      1

## 2 jhon  1/1/2020      1

## 3 susan 1/1/2020      2

## 4 eric  2/4/2020      1

## 5 eric  2/4/2020      2

## 6 susan 2/1/2020      1

## 7 eric  2/4/2020      3

Browse Categories

...