我有一个这样的数据集:
Users Age
1 2
2 7
3 10
4 3
5 8
6 20如何将此数据集分成3个数据集,其中第一个数据集包含所有年龄在0-5岁之间的用户,第二个用户年龄在6-10岁之间,第三个用户年龄在11-15岁之间?
发布于 2014-07-12 08:11:19
您可以在一行代码中结合使用split和cut来完成此操作,从而避免使用针对不同数据范围的一组不同表达式进行子集:
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根据指定的断点拆分数据,而split根据提供的类别拆分数据帧。如果将此计算结果存储到名为l的列表中,则可以使用l[[1]]、l[[2]]和l[[3]]或更详细的命令来访问较小的数据框:
l$`[0,5]`
l$`(5,10]`
l$`(10, 15]`发布于 2014-07-12 07:43:58
首先,为了我的目的,这里是您的数据集:foo=data.frame(Users=1:6,Age=c(2,7,10,3,8,20))
这是您的第一个0-5岁的数据集:subset(foo,Age<=5&Age>=0)
Users Age
1 1 2
4 4 3这是你的第二个6-10岁的孩子:subset(foo,Age<=10&Age>=6)
Users Age
2 2 7
3 3 10
5 5 8您的第三个(使用subset(foo,Age<=15&Age>=11))是空的-您的最后一个Age观察值超过15。
还请注意,5和6或10和11之间的小数年龄(例如5.1,10.5)将被排除,因为此代码与您的问题非常匹配。如果你想让年龄小于6岁的人加入第一组,只需将代码修改为subset(foo,Age<6&Age>=0)即可。如果您更喜欢第二组中有Age=5.1的虚构人物,那么该组的代码应该是subset(foo,Age<=10&Age>5)。
发布于 2020-02-11 04:13:39
我们还可以使用data.table包中的between函数。
# Create a data frame
dat <- data.frame(Users = 1:7, Age = c(2, 7, 10, 3, 8, 12, 15))
# Convert the data frame to data table by reference
# (data.table is also a data.frame)
setDT(dat)
# Define a list with the cut pairs
cuts <- list(c(0, 5), c(6, 10), c(11, 15))
# Cycle through dat and cut it into list of data tables by the values in Age
# matching the defined cuts
lapply(X = cuts, function(i) {
dat[between(x = dat[ , Age], lower = i[1], upper = i[2])]
})输出:
[[1]]
Users Age
1: 1 2
2: 4 3
[[2]]
Users Age
1: 2 7
2: 3 10
3: 5 8
[[3]]
Users Age
1: 6 12
2: 7 15许多其他的事情也是可能的,包括分组,data.table是相当灵活的。
https://stackoverflow.com/questions/24707936
复制相似问题