R: Create a column with values based on grouping specific rows

2.2k views Asked by At

Here is a sample data frame,

ID <- c(101,102,103,201,202,203,301,302,303,401,402,403) 
Point_A <- c(10,20,30,40,50,60,70,80,90,100,110,120) 
df <- data.frame(ID,Point_A)

     ID  Point_A
1    101   10 
2    102   20 
3    103   30 
4    201   40 
5    202   50 
6    203   60 
7    301   70 
8    302   80  
9    303   90  
10   401   100 
11   402   110 
12   403   120 

I want to create a column named Type in df with 2 values A & B. Type A groups (101,102,103,401,402,403) together & Type B groups (201,202,203,301,302,303) together.

My Desired output is

     ID  Point_A Type 
1    101   10     A
2    102   20     A 
3    103   30     A 
4    401   100    A 
5    402   110    A 
6    403   120    A 
7    201   40     B 
8    202   50     B  
9    203   60     B  
10   301   70     B 
11   302   80     B 
12   303   90     B   

Note that the order has also changed. I am just knowing how to do this. Please suggest some ways to get around this.

1

There are 1 answers

7
akrun On BEST ANSWER

Try

 df$Type <- c('B', 'A')[(df$ID %in% c(101:103, 401:403))+1L]

Or

 df$Type <-  c('A', 'B')[(df$ID>103 & df$ID<401)+1L]

 df <- df[order(df$Type),]
 row.names(df) <- NULL
 df
    ID Point_A Type
1  101      10    A
2  102      20    A
3  103      30    A
4  401     100    A
5  402     110    A
6  403     120    A
7  201      40    B
8  202      50    B
9  203      60    B
10 301      70    B
11 302      80    B
12 303      90    B

Update

For 3 groups, creating an example vector

 v1 <- c(df$ID, c(501, 502, 503, 601, 602, 603))
 c('A', 'B', 'C')[(v1 >103 & v1 <401)+ 2*(v1>=501)+1L]
 #[1] "A" "A" "A" "B" "B" "B" "B" "B" "B" "A" "A" "A" "C" "C" "C" "C" "C" "C"

Or

 library(car)
 recode(v1, '101:103="A";401:403="A";201:303="B";else="C"')
 #[1] "A" "A" "A" "B" "B" "B" "B" "B" "B" "A" "A" "A" "C" "C" "C" "C" "C" "C"