【问题标题】:Add a vector based on previous vectors基于先前向量添加向量
【发布时间】:2016-05-13 19:10:44
【问题描述】:

这是我拥有的数据:

round<-rep(1:5,4)
players<-rep(1:2, c(10,10))
decs<-sample(1:3,20,replace=TRUE)
game<-rep(rep(1:2,c(5,5)),2)
gamematrix<-cbind(players,game,round,decs)
gamematrix

这是输出:

     players game round decs
 [1,]       1    1     1    2
 [2,]       1    1     2    2
 [3,]       1    1     3    1
 [4,]       1    1     4    2
 [5,]       1    1     5    1
 [6,]       1    2     1    1
 [7,]       1    2     2    1
 [8,]       1    2     3    2
 [9,]       1    2     4    1
[10,]       1    2     5    3
[11,]       2    1     1    2
[12,]       2    1     2    1
[13,]       2    1     3    3
[14,]       2    1     4    3
[15,]       2    1     5    3
[16,]       2    2     1    3
[17,]       2    2     2    2
[18,]       2    2     3    1
[19,]       2    2     4    1
[20,]       2    2     5    2 

现在,我想添加另一列:“Same Choice”,如果同一游戏中的同一玩家在下一轮做出与上一轮相同的决定,我想成为“1”圆形的。例如,对于玩家 1,输出应为:c(0,1,0,0,0,0,1,0,0,0)。有什么想法我该怎么做?

谢谢!

【问题讨论】:

  • with(data.frame(gamematrix), ave(decs, players, game, FUN=function(x) c(0, !diff(x) )))
  • 顺便说一句,在生成随机数据之前最好使用set.seed,所以我们都在看同一件事。 (见下面 lmo 的回答。)

标签: r vector


【解决方案1】:

这是data.table 的回答:

# set seed
set.seed(1234)

# load data
round<-rep(1:5,4)
players<-rep(1:2, c(10,10))
decs<-sample(1:3,20,replace=TRUE)
game<-rep(rep(1:2,c(5,5)),2)
gamematrix<-cbind(players,game,round,decs)

library(data.table)
dt <- data.table(gamematrix)
dt[, .(decs=decs, lag=c(0,head(decs,-1)), 
                  sameDec=as.integer(decs==c(NA,head(decs,-1)))),
   by=c("players","game")]

我包含了滞后项,以便您进行验证。

@Frank 使用shift 的建议更简洁(而且可能更快):

dt[, .(decs=decs, lag=shift(decs, 1), 
                  sameDec=as.integer(decs==shift(decs, 1))),
by=c("players","game")]

与我手动编码的延迟相比。

【讨论】:

  • 我猜惯用的方式会使用shift 而不是手动构建的滞后,也许像dt[, same := decs != shift(decs), by=.(players, game)] (请注意,这会为每场比赛的第一轮提供 NA... 我认为它应该.)
  • 我修复了 NA 问题。你是对的,在那里有一个有效的值是一个坏主意。我正在努力在我的代码中包含这些data.table 函数...感谢shift 中的提示。
  • 谢谢,我在测试时使用了data.table()
【解决方案2】:

以下代码将起作用

library(dplyr)
gamematrix %>% as.data.frame %>% group_by(players, game) %>% mutate(new_col = ifelse(decs == lag(decs), 1, 0) )
gamematrix$new_col[is.na(gamematrix$new_col)]<- 0

【讨论】:

  • 谢谢弗兰克,我忘了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多