Chang
Chang

Reputation: 35

R: How to divide a data frame by column values?

Suppose I have a data frame with 3 columns and 10 rows as follows.

#      V1     V2     V3
#      10     24     92
#      13     73     100
#      25     91     120
#      32     62     95
#      15     43     110
#      28     54     84
#      30     56     71
#      20     82     80
#      23     19     30
#      12     64     89

I want to create sub-dataframes that divide the original by the values of V1. For example, the first data frame will have the rows with values of V1 from 10-14, the second will have the rows with values of V1 from 15-19, the third from 20-24, etc.

What would be the simplest way to make this?

Upvotes: 2

Views: 419

Answers (1)

MrFlick
MrFlick

Reputation: 206197

So if this is your data

dd<-data.frame(
    V1=c(10,13,25,32,15,38,30,20,23,13),
    V2=c(24,73,91,62,43,54,56,82,19,64),
    V3=c(92,100,120,95,110,84,71,80,30,89)
)

then the easiest way to split is using the split() command. And since you want to split in ranges, you can use the cut() command to create those ranges. A simple split can be done with

ss<-split(dd, cut(dd$V1, breaks=seq(10,35,by=5)-1)); ss

split returns a list where each item is the subsetted data.frame. So to get at the data.frame with the values for 10-14, use ss[[1]], and for 15-19, use ss[[2]] etc.

Upvotes: 5

Related Questions