按一列中的因子拆分/子集数据框 [英] Split/subset a data frame by factors in one column

查看:31
本文介绍了按一列中的因子拆分/子集数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是这样的(例如):

ID 速率状态1 24 铝2 35 MN3 46 佛罗里达州4 34 铝5 78 MN6 99 佛罗里达州

数据:

structure(list(ID = 1:6, Rate = c(24L, 35L, 46L, 34L, 78L, 99L),状态 = 结构(c(1L, 3L, 2L, 1L, 3L, 2L),.Label = c("AL","FL","MN"),class = "因子")),.Names = c("ID", "Rate", "State"),class = "data.frame", row.names = c(NA, -6L))

我想按州拆分数据,我想获得如下 3 个数据集:

数据集1ID 速率状态1 24 铝4 34 铝数据集 2ID 速率状态2 35 MN5 78 MN数据集 3ID 速率状态3 46 佛罗里达州6 99 佛罗里达州

我应该使用什么功能?

我正在考虑拆分或子集功能,但仍然没有任何线索.

解决方案

我们可以使用split:

mylist <- split(df, df$State)我的列表$ALID 速率状态1 1 24 铝4 4 34 铝$FLID 速率状态3 3 46 佛罗里达州6 6 99 佛罗里达州$MNID 速率状态2 2 35 MN5 5 78 MN

访问元素编号:

mylist[[1]]

或按名称:

mylist$ALID 速率状态1 1 24 铝4 4 34 铝

<块引用>

?split

说明

split 将向量 x 中的数据分成由 f 定义的组.替换形式替换对应于这种划分的值.unsplit 反转 split 的效果.

My data is like this (for example):

ID  Rate    State
1   24  AL
2   35  MN
3   46  FL
4   34  AL
5   78  MN
6   99  FL

Data:

structure(list(ID = 1:6, Rate = c(24L, 35L, 46L, 34L, 78L, 99L),
               State = structure(c(1L, 3L, 2L, 1L, 3L, 2L),
                                 .Label = c("AL","FL", "MN"),
                                 class = "factor")),
          .Names = c("ID", "Rate", "State"),
          class = "data.frame", row.names = c(NA, -6L))

I want to split the data by state and I want to get 3 data sets like below:

data set 1
ID  Rate    State
1   24  AL
4   34  AL
data set 2
ID  Rate    State
2   35  MN
5   78  MN
data set 3
ID  Rate    State
3   46  FL
6   99  FL

What function I should use?

I was thinking about split or subset function, but still have no clue yet.

解决方案

We could use split:

mylist <- split(df, df$State)

mylist
$AL
  ID Rate State
1  1   24    AL
4  4   34    AL

$FL
  ID Rate State
3  3   46    FL
6  6   99    FL

$MN
  ID Rate State
2  2   35    MN
5  5   78    MN

To access elements number:

mylist[[1]]

or by name:

mylist$AL
  ID Rate State
1  1   24    AL
4  4   34    AL

?split

Description

split divides the data in the vector x into the groups defined by f. The replacement forms replace values corresponding to such a division. unsplit reverses the effect of split.

这篇关于按一列中的因子拆分/子集数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆