【问题标题】:R: Counting the cumulative length of a factor in data.frameR:计算data.frame中因子的累积长度
【发布时间】:2016-03-29 19:30:13
【问题描述】:

我有这个数据库:

Time = c("2016-03-01","2016-03-02","2016-03-03","2016-03-02","2016-03-03","2016-03-02")
match = c("a","b","c","a","b","c") 
names = c("julien","julien","julien", "mathieu","mathieu","simon") 
df = data.frame(Time, names, match) 
df = df[order(Time),]
df
        Time   names match
1 2016-03-01  julien     a
2 2016-03-02  julien     b
4 2016-03-02 mathieu     a
6 2016-03-02   simon     c
3 2016-03-03  julien     c
5 2016-03-03 mathieu     b

我希望每个玩家在一段时间内的累计比赛数作为一个新列。我想知道,在任何给定时间,每个球员参加了多少场比赛。像这样:

        Time   names match nb.of.match.played
1 2016-03-01  julien     a                  1
2 2016-03-02  julien     b                  2
4 2016-03-02 mathieu     a                  1
6 2016-03-02   simon     c                  1
3 2016-03-03  julien     c                  3
5 2016-03-03 mathieu     b                  2 

这似乎很容易做到,但我每次都尝试了很多失败的结果。 感谢您的帮助!

【问题讨论】:

  • 显示你的一些代码 sn-ps 尽可能地工作,我们可以看看它
  • 抱歉,我没有任何有形的线索(代码 sn-ps)值得展示......我尝试了这个解决方案:stackoverflow.com/questions/22843286/…,但我认为目标不相似。跨度>

标签: database cumulative-frequency


【解决方案1】:

我用趋势解决了我的问题cumsum using ddply

但我认为 cumsum 不适用于因子的长度,所以我有一列“1”,cumsum 可以在上面工作。

Time = c("2016-03-01","2016-03-02","2016-03-03","2016-03-02","2016-03-03","2016-03-02")
match = c("a","b","c","a","b","c")
names = c("julien","julien","julien", "mathieu","mathieu","simon")
df = data.frame(Time, names, match) 
df = df[order(Time),]
df$nb = 1
df
        Time   names match nb
1 2016-03-01  julien     a  1
2 2016-03-02  julien     b  1
4 2016-03-02 mathieu     a  1
6 2016-03-02   simon     c  1
3 2016-03-03  julien     c  1
5 2016-03-03 mathieu     b  1

within(df, {
  nb.match <- ave(nb, names, FUN = cumsum)
})
df
        Time   names match nb nb.match
1 2016-03-01  julien     a  1        1
2 2016-03-02  julien     b  1        2
4 2016-03-02 mathieu     a  1        1
6 2016-03-02   simon     c  1        1
3 2016-03-03  julien     c  1        3
5 2016-03-03 mathieu     b  1        2

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多