0

I would like to create an incrementing variable (Id1 or Id2) from 2 others variables (Var1 and Var2).

Thank you. Elodie

EDIT (reproductible example for Aaron Montgomery) I want to create an incrementing variable : "Id". The value of "Id" changes if VarA is a new value and if VarB is a new value. See in particular when Id = 4 in the expected table.

data_example <- data.table::fread("
VarA    VarB 
A1  B1    
A1  B2    
A1  B3 
A1  B4       
A2  B5   
A3  B6    
A4  B7   
A5  B7    
A5  B8   
A6  B9    
A7  B10    
A8  B10   
A9  B10")

Expected table

VarA    VarB    Id
A1  B1  1
A1  B2  1 
A1  B3  1  
A1  B4  1  
A2  B5  2
A3  B6  3 
A4  B7  4
A5  B7  4 
A5  B8  4
A6  B9  5  
A7  B10 6 
A8  B10 6
A9  B10 6
1
  • 1
    I can't follow what you're asking for... Can you provide your expected output? A reproducible example (in the form of code we can put into our R consoles, perhaps generated by dput()) would also be helpful. Commented May 28, 2020 at 15:41

1 Answer 1

0

Here is one solution using the tidyverse

library(tidyverse)
data_example <- data.table::fread("
Var1    Var2    Id1 Id2
604211  1001    3   1
604211  1093    3   1
604211  1146    3   1
604211  1319    3   1
635348  1002    5   2
634849  1005    5   2
620861  1004    4   3
622281  1004    4   3
622281  1041    4   3
600044  1100    1   4
600049  1033    2   5
607692  1033    2   5
612595  1033    2   5")

data_example %>% 
  arrange(Var1,Var2) %>% 
  group_by(Var1) %>% 
  mutate(id1 = group_indices()) %>% 
  group_by(Var2) %>% 
  mutate(id2 = group_indices())
Sign up to request clarification or add additional context in comments.

2 Comments

Your code doesn't work for me. I have just edit my original question.
"Error in mutate_impl(.data, dots) : Evaluation error: argument ".data" is missing, with no default." I think the group_indices function needs at least one variable as parameter, but if I put group_indices(Var1,Var2), group_indices(Var1) or group_indices(Var2), it doesn't give the expected table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.