Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning data less than 5 in one group in r

Tags:

r

I have data set like this:

ID  col1
1   A
2   A
3   A
4   A
5   A
6   B
7   B
8   C
9   D
10  A
11  A
12  A

I want to create a new column that keeps "A" as it is (since its number above 5) and gather all the letters that has number less than 5 in one group called "other" as this example:

ID  col1 col2
1   A     A
2   A     A
3   A     A
4   A     A
5   A     A
6   B     other
7   B     other
8   C     other
9   D     other
10  A      A
11  A      A
12  A      A

can you please help me?

The dataframe: df<-data.frame(Id=seq(1,12),col1=c(rep('A',5),'B','B','C','D',rep('A',3)))

like image 467
Marwah Al-kaabi Avatar asked Jan 24 '23 06:01

Marwah Al-kaabi


1 Answers

library(data.table)
Data <- as.data.table(Data)
Data[, N := .N, col1]
Data[, col2 := ifelse(N < 5, "other", col1)]

like image 133
TobiSonne Avatar answered Feb 04 '23 00:02

TobiSonne