2

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 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

7 Comments

Awesome. Thanks @akrun, How can I extend this to have something like Type C that groups (501,502,503,601,602,603)?
@Sharath If you have many groups, try cut with the required breaks
I am still learning R. I just looked it up. This is what I could do. df$Type <- cut(df$ID, breaks = seq(100, 103, by = 1)). Could you please help me with that?
@Sharath Do you want to code for any other group i.e. Type D or so?
Thanks so much. This is Awesome. Just a quick note, the 501 is assigned A. I ll make the edit now.
|

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.