使用Send()或其他重塑函数,使用多个度量值列从长到宽重塑数据 [英] Reshape data from long to wide with multiple measure columns using spread() or other reshape functions
本文介绍了使用Send()或其他重塑函数,使用多个度量值列从长到宽重塑数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这里已经有很多关于这个话题的问题了。但在我看了几本书后,所有的书都只有一篇《测量》栏目。我仍然不知道如何处理我的数据。
我的数据如下所示,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,]
但我想知道如何使用Send()或其他重塑函数来完成此操作。
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
推荐答案
下面的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
这篇关于使用Send()或其他重塑函数,使用多个度量值列从长到宽重塑数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文