如何将数据从长格式重塑为宽格式 [英] How to reshape data from long to wide format
本文介绍了如何将数据从长格式重塑为宽格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在重新排列以下数据框时遇到问题:
I'm having trouble rearranging the following data frame:
set.seed(45)
dat1 <- data.frame(
name = rep(c("firstName", "secondName"), each=4),
numbers = rep(1:4, 2),
value = rnorm(8)
)
dat1
name numbers value
1 firstName 1 0.3407997
2 firstName 2 -0.7033403
3 firstName 3 -0.3795377
4 firstName 4 -0.7460474
5 secondName 1 -0.8981073
6 secondName 2 -0.3347941
7 secondName 3 -0.5013782
8 secondName 4 -0.1745357
我想重塑它,以便每个唯一的名称"变量都是一个行名,值"作为沿该行的观察值,数字"作为列名.有点像这样:
I want to reshape it so that each unique "name" variable is a rowname, with the "values" as observations along that row and the "numbers" as colnames. Sort of like this:
name 1 2 3 4
1 firstName 0.3407997 -0.7033403 -0.3795377 -0.7460474
5 secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357
我已经看过 melt
和 cast
以及其他一些东西,但似乎没有一个能胜任.
I've looked at melt
and cast
and a few other things, but none seem to do the job.
推荐答案
使用reshape
函数:
reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")
这篇关于如何将数据从长格式重塑为宽格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文