Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reducing number of rows in R

Tags:

r

I am new in R programming language. I have a data set that has 2 columns(ID and Num) like this:

ID    Num
3       8
3      12
4      15
4      18
4      24

But I want to convert it to:

ID    Num
3     8 12
4     15 18 24

3 and 4 are still in column 'ID' but 8 and 12 are in one row near each other, in 'Num' column with 'ID' of 3. And also 4 is in column 'ID' and 15 18 and 24 are in one row near each other, in 'Num' column with ID of 4. Can anyone help me convert original data set to this new type. I searched a lot but I couldn't find R code of this problem anywhere.

like image 541
Mark Olson Avatar asked Dec 13 '25 08:12

Mark Olson


1 Answers

You can also use aggregate

> aggregate(DF$Num~DF$ID, FUN=paste, sep=" ")
  DF$ID     DF$Num
1     3      8, 12
2     4 15, 18, 24

Alternatively, you can use data = parameter of aggregate to get the column names not have the DF$:

aggregate(data=DF, Num~ID, FUN=paste, sep=" ")
#   ID        Num
# 1  3      8, 12
# 2  4 15, 18, 24
like image 82
Jilber Urbina Avatar answered Dec 16 '25 22:12

Jilber Urbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!