简体   繁体   English

R-如何通过更改主要唯一行变量将宽数据集重新格式化为宽数据集

[英]R - How to reformat wide dataset to wider dataset by changing the primary unique row variable

Sorry if this has been asked already and if the title is very confusing. 很抱歉,是否已经有人问过这个问题,以及标题是否很混乱。 I did look and only found questions on reformating where the values of one of the columns were used as column headings in the output dataset. 我确实看了一下,仅发现有关重新格式化其中一列的值在输出数据集中用作列标题的问题。

My dataset is organized so the Filter is the unique value for each row. 我的数据集是有组织的,因此Filter是每一行的唯一值。 I want to change it so the id of the individual within each sampling season is unique for each row since individuals had multiple filters. 我想更改它,以便每个人在每个采样季节内的ID对于每一行都是唯一的,因为每个人都有多个过滤器。 Basically, I want to reformat Table 1 so it looks like Table 2. 基本上,我想重新格式化表1,使其看起来像表2。

Table 1
       id season FilterI 
    1:  1      1       A 
    2:  1      1       B 
    3:  2      1       C 
    4:  2      1       D 
    5:  1      2       E 
    6:  1      2       F 

Table 2
       id season FilterI1 FilterI2
    1:  1      1       A        B
    2:  1      2       E        F
    3:  2      1       C        D

Reshape does not seem to work because none of the columns in the first dataset contain the column headings for the second dataset. Reshape似乎不起作用,因为第一个数据集中的所有列都不包含第二个数据集的列标题。

Using dcast with rowid , change from 'long' to 'wide' (assuming the example data is data.table ) dcastrowid dcast使用,从'long'更改为'wide'(假设示例数据为data.table

library(data.table)
dcast(Table1, id + season ~ paste0("FilterI", rowid(id)), value.var = "FilterI")
#     id season FilterI1 FilterI2
#1:  1      1        A        B
#2:  1      2        E        F
#3:  2      1        C        D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM