R数据帧中的分层索引 [英] Hierarchical indexing in R dataframe

查看:129
本文介绍了R数据帧中的分层索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,我试图读入R中的数据框架,我想知道如何使用分层索引存储它。换句话说,我想使用这样的列名称:

I have a CSV file that I'm trying to read into a dataframe in R, and I was wondering how I might go about storing it with hierarchical indexing. In other words, I want to make something with column names like this:

('a1', 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b1', 'c3'), ('a1', 'b1', 'c4'),
('a1', 'b2', 'c1'), ('a1', 'b2', 'c2'), ('a1', 'b2', 'c3'), ('a1', 'b2', 'c4'),
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24

结果如下:

_________________________________________________
||                      a1                     ||
_________________________________________________
||          b1          ||          b2         ||
_________________________________________________
||  c1 | c2 | c3 | c4   ||   c1 | c2 | c3 | c4 ||
_________________________________________________
||  1  |  2 |  3 |  4   ||    5 |  6 |  7 |  8 ||
||  9  | 10 | 11 | 12   ||   13 | 14 | 15 | 16 ||
||  17 | 18 | 19 | 20   ||   21 | 22 | 23 | 24 ||
_________________________________________________

转换为R数据框时。我怎么会这样做呢?我是R的新手,虽然我非常熟悉Python中的Pandas数据框架。感谢

When converted into an R dataframe. How exactly would I go about doing that? I am new to R although I'm pretty familiar with Pandas dataframes in Python. Thanks

推荐答案

我不想把这个放在一个答案,但它是唯一的方式来说明我在说什么。在R中,我们将采用类似您提供的层次数据,并存储如下:

I hesitate to put this in an answer, but it's the only way to illustrate what I'm talking about. In R, we would take hierarchical data like what you provided and store it like this:

df <- data.frame(grp1 = 'a1',
                 grp2 = rep(c('b1','b2'),each = 4),
                 grp3 = rep(c('c1','c2','c3','c4'),times = 2))
> df
  grp1 grp2 grp3
1   a1   b1   c1
2   a1   b1   c2
3   a1   b1   c3
4   a1   b1   c4
5   a1   b2   c1
6   a1   b2   c2
7   a1   b2   c3
8   a1   b2   c4

如果您有其他群组或级别,则可以添加更多列,并根据需要复制之前的列。

If you have further groups, or levels, you'd add more columns and replicate the previous columns as needed.

这篇关于R数据帧中的分层索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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