How to assign values to cases by group

This is sample of data I am working with:

enter image description here

Here is the data splited into different files, one for 2 elements by group and anothe one with 3 elements by group

https://drive.google.com/drive/folders/13NcZ1eDRz7RfPIV0w-bOsF6kS1ePSQ9j?usp=sharing

In the column inspection I want to assing this codes by group (group variables are Code, Area, Floor and Box).

For each group combination:

How can I make this adjustment to inspection variable by each case groups to get the result in this image?

enter image description here

Then, I have cases with 3 elements per group:

enter image description here

For each group combination:

enter image description here

How can I do that asignation?

Upvotes: 0

Views: 72

Answers (1)

langtang
langtang

Reputation: 24722

How about just using the order of Result to rearrange c(2,1), like this:

df %>% 
  group_by(Code, Area, Floor, Box) %>% 
  mutate(Inspection = c(2,1)[order(Result)])

Output:

  Code   Area Floor   Box Result Inspection
  <chr> <dbl> <dbl> <dbl>  <dbl>      <dbl>
1 10101    11   108     1      4          1
2 10101    11   108     1      1          2
3 10101    11    89     1      1          2
4 10101    11    89     1      1          1
5 10101    11    90     1      1          2
6 10101    11    90     1      3          1

Upvotes: 1

Related Questions