如何透视表以使列从R中的可变行值 [英] How to pivot a table to make columns fro a variable row values in R
本文介绍了如何透视表以使列从R中的可变行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个data.frame,其列为:Month,Store和Demand.
I have a data.frame with the columns: Month, Store and Demand.
Month Store Demand
Jan A 100
Feb A 150
Mar A 120
Jan B 200
Feb B 230
Mar B 320
我需要围绕它进行旋转以制作一个新的data.frame或每个月带有列的数组,例如:
I need to pivot it around to make a new data.frame or array with columns for each month, store e.g.:
Store Jan Feb Mar
A 100 150 120
B 200 230 320
非常感谢您的帮助.我刚开始使用R.
Any help is very much appreciated. I have just started with R.
推荐答案
> df <- read.table(textConnection("Month Store Demand
+ Jan A 100
+ Feb A 150
+ Mar A 120
+ Jan B 200
+ Feb B 230
+ Mar B 320"), header=TRUE)
因此,您的月份"列很可能是按字母顺序排列的级别的一个因素 ()
So in all likelihood your Month column is a factor with levels sorted alphabetically ()
> df$Month <- factor(df$Month, levels= month.abb[1:3])
# Just changing levels was not correct way to handle the problem.
# Need to use within a factor(...) call.
> xtabs(Demand ~ Store+Month, df)
Month
Store Jan Feb Mar
A 100 150 120
B 200 230 320
一种不太明显的方法(因为"I"函数返回其参数):
A slightly less obvious method (since the 'I' function returns its argument):
> with(df, tapply(Demand, list(Store, Month) , I) )
Jan Feb Mar
A 100 150 120
B 200 230 320
这篇关于如何透视表以使列从R中的可变行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文