请注意,这与问题" How to reshape data from long to wide format?"有两种方式:
tidyverse
解决方案是首选。执行:
set.seed(14)
df <- data.frame(geo = LETTERS[1:2], time = c(2000,2000,2001,2001),
X = rnorm(4, 0, 1),
Y = rnorm(4, 0, 2))
head(df)
产生类似的东西:
geo time X Y
1 A 2000 -0.6618498 -0.07228116
2 B 2000 1.7189542 2.46389035
3 A 2001 2.1216670 -0.12976154
4 B 2001 1.4971537 2.13798746
我想要做的是重塑spread
time
,最后得到两行geo
A
和B
的值。
这会产生类似的东西:
geo X.2000 Y.2000 X.2001 Y.2001
A -0.6618498 -0.07228116 2.1216670 -0.12976154
B 1.7189542 2.46389035 1.4971537 2.13798746
答案 0 :(得分:2)
整洁方法是:
library(tidyr)
library(dplyr)
df %>%
gather(key, value, -c(geo, time)) %>%
unite(key, c(key, time), sep = ".") %>%
spread(key, value)
# geo X.2000 X.2001 Y.2000 Y.2001
# 1 A -0.6618498 2.121667 -0.07228116 -0.1297615
# 2 B 1.7189542 1.497154 2.46389035 2.1379875
答案 1 :(得分:0)
我们可以使用reshape
功能
reshape(df, direction = "wide", idvar = "geo", timevar = "time")
它为我们提供了您希望的结果
geo X.2000 Y.2000 X.2001 Y.2001
1 A -0.6618498 -0.07228116 2.121667 -0.1297615
2 B 1.7189542 2.46389035 1.497154 2.1379875