首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用R来操作数据

如何使用R来操作数据
EN

Stack Overflow用户
提问于 2014-07-29 19:17:06
回答 1查看 102关注 0票数 0

我正在尝试进行一项预测分析,其中x年的指标将预测年份x+1。

如果我有这样的数据,我想使用R在SQL中执行相当于更新查询的操作:

代码语言:javascript
复制
x <- c("Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer",
       "Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer",
       "Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer")
y <- c("2012", "2012", "2012", "2012", 
       "2013", "2013", "2013", "2013", 
       "2014", "2014", "2014", "2014")
z <- c(100, 50, 75, 0, 
       110, 75, 0, 25, 
       125, 25, 10, 50)

df <- data.frame(x, y, z)

colnames(df) <- c("Name", "Year", "Sales")

print(df)

            Name Year Sales
1   Randy Watson 2012   100
2  Cleo McDowell 2012    50
3   Darryl Jenks 2012    75
4   Jaffe Joffer 2012     0
5   Randy Watson 2013   110
6  Cleo McDowell 2013    75
7   Darryl Jenks 2013     0
8   Jaffe Joffer 2013    25
9   Randy Watson 2014   125
10 Cleo McDowell 2014    25
11  Darryl Jenks 2014    10
12  Jaffe Joffer 2014    50

我希望最终输出如下所示:

代码语言:javascript
复制
print(df)
           Name YearX YearX1
1  Randy Watson   100   110
2 Cleo McDowell    50    75
3  Darryl Jenks    75     0
4  Jaffe Joffer     0    25

...

我怎样才能在R中做到这一点?我知道如何在SQL中这样做(尽管我不想使用sqldf,除非这是最好的方法)。

谢谢。

编辑:,下面的解决方案不是我想要的。虽然它有效,如果只有两年,我的数据有10年。我不需要名字,Year1,Year2,Year3等等。我只想知道名字,YearX,YearX+1,对不起,如果我不清楚的话。

EN

回答 1

Stack Overflow用户

发布于 2014-07-29 19:33:27

像这样

代码语言:javascript
复制
# I took the liberty of rearranging your working example a bit   
df <- data.frame(
           Name = c("Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer",
                    "Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer"),
           Year = c("2013", "2013", "2013", "2013", "2014", "2014", "2014", "2014"),
           Sales = c(100, 50, 75, 0, 110, 75, 0, 25))

reshape(df, idvar = "Name", timevar = "Year", direction = "wide")

           Name Sales.2013 Sales.2014
1  Randy Watson        100        110
2 Cleo McDowell         50         75
3  Darryl Jenks         75          0
4  Jaffe Joffer          0         25

或者密切关注你的问题

代码语言:javascript
复制
df_wide <- reshape(df, idvar = "Name", timevar = "Year", direction = "wide")

colnames(df_wide) <- c("Name", "Year0", "Year1") 

print(df_wide)
           Name Year0 Year1
1  Randy Watson   100   110
2 Cleo McDowell    50    75
3  Darryl Jenks    75     0
4  Jaffe Joffer     0    25

一些替代方法应该给出相同的结果。

代码语言:javascript
复制
library(reshape)
cast(df, Name ~ Year)

xtabs(Sales  ~  Name + Year, data = df)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25023265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档