将数据框从长改成宽
Reshape a data frame from long to wide
我在更改 df 的形状时遇到了一些问题。
数据:
id <- c(1,2,3,4,1,4,1,2,3)
a <- c("A","B","C","D","A","D","A","B","C")
b <- c(1,1,1,1,2,2,3,3,3)
c <- c(12,10,12,23,16,17,7,9,7)
df <- data.frame(id,a,b,c)
这导致:
id a b c
1 A 1 12
2 B 1 10
3 C 1 12
4 D 1 23
1 A 2 16
4 D 2 17
1 A 3 7
2 B 3 9
3 C 3 7
我想要获得以下结构,其中 b 列对应于月份:
id a 1 2 3
1 A 12 16 7
2 B 10 NA 9
3 C 12 NA 7
4 D 23 17 NA
我试过了:
df2 <- reshape(df, timevar = "b", idvar = c("id", "a", "c"), direction = "wide")
但这并没有多大帮助...
试试这个
library(reshape2)
dcast(df, id + a ~ b, value.var = "c")
# id a 1 2 3
# 1 1 A 12 16 7
# 2 2 B 10 NA 9
# 3 3 C 12 NA 7
# 4 4 D 23 17 NA
或使用 reshape
稍微修改您的解决方案
reshape(df, timevar = "b", idvar = c("id", "a"), direction = "wide")
# id a 1 2 3
# 1 1 A 12 16 7
# 2 2 B 10 NA 9
# 3 3 C 12 NA 7
# 4 4 D 23 17 NA
使用tidyr
library(tidyr)
spread(df, b, c)
# id a 1 2 3
#1 1 A 12 16 7
#2 2 B 10 NA 9
#3 3 C 12 NA 7
#4 4 D 23 17 NA
我在更改 df 的形状时遇到了一些问题。
数据:
id <- c(1,2,3,4,1,4,1,2,3)
a <- c("A","B","C","D","A","D","A","B","C")
b <- c(1,1,1,1,2,2,3,3,3)
c <- c(12,10,12,23,16,17,7,9,7)
df <- data.frame(id,a,b,c)
这导致:
id a b c
1 A 1 12
2 B 1 10
3 C 1 12
4 D 1 23
1 A 2 16
4 D 2 17
1 A 3 7
2 B 3 9
3 C 3 7
我想要获得以下结构,其中 b 列对应于月份:
id a 1 2 3
1 A 12 16 7
2 B 10 NA 9
3 C 12 NA 7
4 D 23 17 NA
我试过了:
df2 <- reshape(df, timevar = "b", idvar = c("id", "a", "c"), direction = "wide")
但这并没有多大帮助...
试试这个
library(reshape2)
dcast(df, id + a ~ b, value.var = "c")
# id a 1 2 3
# 1 1 A 12 16 7
# 2 2 B 10 NA 9
# 3 3 C 12 NA 7
# 4 4 D 23 17 NA
或使用 reshape
reshape(df, timevar = "b", idvar = c("id", "a"), direction = "wide")
# id a 1 2 3
# 1 1 A 12 16 7
# 2 2 B 10 NA 9
# 3 3 C 12 NA 7
# 4 4 D 23 17 NA
使用tidyr
library(tidyr)
spread(df, b, c)
# id a 1 2 3
#1 1 A 12 16 7
#2 2 B 10 NA 9
#3 3 C 12 NA 7
#4 4 D 23 17 NA