将数据从多行转换为多列[重复]

时间:2022-12-27 23:42:42

This question already has an answer here:

这个问题在这里已有答案:

I have data that comes out of a DB in a normalized way with a field for year, state, and value.

我有一个以标准化方式从数据库中获取的数据,其中包含年份,状态和值的字段。

I would like to do analysis on the data and need it formatted where each year is a field and not a record.So I would like the data where each record is a state and then there's a field for each year and each value for those fields are the value for that year and that state.

我想对数据进行分析,并且需要格式化每年是一个字段而不是记录。所以我想要每个记录都是状态的数据,然后每年都有一个字段和这些字段的每个值是那一年和那个州的价值。

Is there a command for doing this?

这样做有命令吗?

So I have:

所以我有:

State  Year  Value  
   KY  1998     56  
   KY  1997     78  
   IL  1998     48  
   IL  1997     72

and I want:

而且我要:

State  1997_value  1998_value  
   KY          78          56  
   IL          72          48

3 个解决方案

#1


20  

You want to use the reshape() function.

您想使用reshape()函数。

reshape(data, idvar="State", timevar="Year", direction="wide")

#2


6  

Another option is to use the reshape package, created by the inimitable Hadley Wickham:

另一种选择是使用由无法模仿的Hadley Wickham创建的重塑包:

library(reshape)

tuna<-melt(data,id.vars=c("State","Year"))

cast(tuna,State~Year~variable)

#3


2  

You can even combine the melt and cast lines into one call to the recast function.

您甚至可以将熔化线和铸造线组合成对重铸功能的一次调用。

ds <- data.frame(State = c("KY", "KY", "IL", "IL"), 
Year = c(1998, 1997, 1998, 1997), 
Value = c(56, 78, 48, 72))

library(reshape)
recast(ds, State ~ Year, id.var = c("State", "Year"))

#1


20  

You want to use the reshape() function.

您想使用reshape()函数。

reshape(data, idvar="State", timevar="Year", direction="wide")

#2


6  

Another option is to use the reshape package, created by the inimitable Hadley Wickham:

另一种选择是使用由无法模仿的Hadley Wickham创建的重塑包:

library(reshape)

tuna<-melt(data,id.vars=c("State","Year"))

cast(tuna,State~Year~variable)

#3


2  

You can even combine the melt and cast lines into one call to the recast function.

您甚至可以将熔化线和铸造线组合成对重铸功能的一次调用。

ds <- data.frame(State = c("KY", "KY", "IL", "IL"), 
Year = c(1998, 1997, 1998, 1997), 
Value = c(56, 78, 48, 72))

library(reshape)
recast(ds, State ~ Year, id.var = c("State", "Year"))