[英]reshaping data frame in R: changing a column to row name
我在R中工作。我有一個包含三列的數據框。 A欄包含公司名稱,b欄包含日期,c欄包含價格
>
A B C
Apple 2012/06/01 410
Coke 2012/06/01 210
Pepsi 2012/06/01 152
Apple 2012/06/02 420
Coke 2012/06/02 220
Pepsi 2012/06/02 142
Apple 2012/06/03 440
Coke 2012/06/03 260
Pepsi 2012/06/03 122
我想重塑數據框,以使公司名稱變為行名稱,日期變為列名稱,而價格在相應的單元格中
Apple Coke Pepsi
2012/06/03 410 210 152
2012/06/03 420 220 142
2012/06/03 460 260 162
我嘗試使用melt和dcast函數,但找不到解決方案。
您可以使用tidyr::spread
library(tidyr)
spread(d,A,C)
產量
B Apple Coke Pepsi
1 2012/06/01 410 210 152
2 2012/06/02 420 220 142
3 2012/06/03 440 260 122
數據
d <- read.table(text=" A B C
Apple 2012/06/01 410
Coke 2012/06/01 210
Pepsi 2012/06/01 152
Apple 2012/06/02 420
Coke 2012/06/02 220
Pepsi 2012/06/02 142
Apple 2012/06/03 440
Coke 2012/06/03 260
Pepsi 2012/06/03 122",head=TRUE)
您可以使用reshape2
包中的dcast()
函數將數據從“長”格式dcast()
為“寬”格式:
library(reshape2)
dcast(df1, B ~ A , value.var = "C")
# B Apple Coke Pepsi
#1 2012/06/01 410 210 152
#2 2012/06/02 420 220 142
#3 2012/06/03 440 260 122
數據
df1 <- structure(list(A = c("Apple", "Coke", "Pepsi", "Apple", "Coke",
"Pepsi", "Apple", "Coke", "Pepsi"),
B = c("2012/06/01", "2012/06/01", "2012/06/01", "2012/06/02",
"2012/06/02", "2012/06/02", "2012/06/03", "2012/06/03",
"2012/06/03"),
C = c(410L, 210L, 152L, 420L, 220L, 142L, 440L, 260L, 122L)),
.Names = c("A", "B", "C"),
class = "data.frame", row.names = c(NA, -9L))
此網頁是源示例,提供了有關已使用命令的說明。 它還描述了轉換數據格式的其他可能性。
我們可以使用基本包stats
的函數reshape
功能:
reshape(df, idvar='B', timevar='A', direction='wide')
輸出:
B C.Apple C.Coke C.Pepsi
1 2012/06/01 410 210 152
4 2012/06/02 420 220 142
7 2012/06/03 440 260 122
數據:
df <- structure(list(A = c("Apple", "Coke", "Pepsi", "Apple", "Coke",
"Pepsi", "Apple", "Coke", "Pepsi"),
B = c("2012/06/01", "2012/06/01", "2012/06/01", "2012/06/02",
"2012/06/02", "2012/06/02", "2012/06/03", "2012/06/03",
"2012/06/03"),
C = c(410L, 210L, 152L, 420L, 220L, 142L, 440L, 260L, 122L)),
.Names = c("A", "B", "C"),
class = "data.frame", row.names = c(NA, -9L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.