I have a data set like this:
Users Age
1 2
2 7
3 10
4 3
5 8
6 20
How do I split this data set i
You can combine split
with cut
to do this in a single line of code, avoiding the need to subset with a bunch of different expressions for different data ranges:
split(dat, cut(dat$Age, c(0, 5, 10, 15), include.lowest=TRUE))
# $`[0,5]`
# Users Age
# 1 1 2
# 4 4 3
#
# $`(5,10]`
# Users Age
# 2 2 7
# 3 3 10
# 5 5 8
#
# $`(10,15]`
# [1] Users Age
# <0 rows> (or 0-length row.names)
cut
splits up data based on the specified break points, and split
splits up a data frame based on the provided categories. If you stored the result of this computation into a list called l
, you could access the smaller data frames with l[[1]]
, l[[2]]
, and l[[3]]
or the more verbose:
l$`[0,5]`
l$`(5,10]`
l$`(10, 15]`