使用spread()或其他重塑函数,使用多个度量列将数据从长到宽重塑

时间:2018-07-17 19:29:36

标签: r reshape spread

我知道这里已经有很多关于该主题的问题。但是,在我查看了几个之后,所有这些都只有一个“度量”列。我仍然不知道如何处理我的数据。

我的数据如下所示,其中X1,X2表示不同的区域。因此该数据集中的每一列代表了一个地区收集的所有年龄。

age     X1   X2
age 0   2    2
age 1   2    2 
age 2   2    3
  ... 

我想将数据重塑为宽格式:

     age 0  age 1 age 2
X1    2      2     2 
X2    2      2     3
     ...

要重新创建数据集,请使用

data <-structure(list(age = c("age 0", "age 1", "age 2", "age 3", "age 4", 
"age 5", "age 6", "age 7", "age 8", "age 9", "age 10", "age 11", 
"age 12"), X1 = c(2, 2, 2, 4, 7, 12, 19, 22, 18, 11, 6, 3, 3), 
    X2 = c(2, 2, 3, 4, 8, 14, 21, 24, 20, 12, 7, 4, 3)), row.names = c("0", 
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
), class = "data.frame")

移调可以达到目的:

rownames(data)<- data[,1]
wide <- t(data)[2:3,] 

但是我不知道如何使用spread()或其他重塑函数来做到这一点。

library(tidyr)
wide <- spread(data, age, X1)
#X2 remains the same, and X1 is not correcty reshaped.
wide <- spread(data, age, X1, X2)
#Error in spread.data.frame(data, age, X1, X2) : object 'X2' not found

3 个答案:

答案 0 :(得分:1)

下面的tidyr溶液。您需要将区域收集到一列中才能进行传播。

library(tidyr)
data %>% gather(region,val,-age) %>% spread(age,val)  

#   region age 0 age 1 age 10 age 11 age 12 age 2 age 3 age 4 age 5 age 6 age 7 age 8 age 9
# 1     X1     2     2      6      3      3     2     4     7    12    19    22    18    11
# 2     X2     2     2      7      4      3     3     4     8    14    21    24    20    12

答案 1 :(得分:0)

您似乎可以通过转置数据来完成此操作:

t(data)

如果由于某种原因而设置重塑数据,则可以使用reshape包,将数据完全转换为长格式,然后将其转换为宽格式:

library(reshape2)
dcast(melt(data, measure.vars = c("X1","X2")), variable~age)    

答案 2 :(得分:0)

或者仅在基数R中

#pragma once

#include <string>
#include <iostream>
#include <typeinfo>

#include <boost/serialization/base_object.hpp>
#include <boost/serialization/access.hpp>

#include "baseclass.h"

class DerivedClass :  public BaseClass
{
public:
    DerivedClass() : BaseClass("DerivedClass") {}
    DerivedClass(std::string custom) : BaseClass("DerivedClass") {
        data = custom;
    }

    virtual ~DerivedClass() {}

    void printData() override {
        std::cout << typeid(*this).name() << ": " << name << " AND " << data << std::endl;
    }

protected:
    std::string data;

private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) {
        ar & (boost::serialization::base_object<BaseClass>(*this));
        ar & (data);
    }
};