我有以下数据框:
game <- c('game1','game1','game2','game2','game2','game3','game4', 'game4')
shot_number <- c(1,NA,1,NA,NA,1,1,NA)
df <- data.frame(game, shot_number)
game shot_number
game1 1
game1 NA
game2 1
game2 NA
game2 NA
game3 1
game4 1
game4 NA
我想通过在上面的行中加1来填充NA,所以df如下所示:
game shot_number
game1 1
game1 2
game2 1
game2 2
game2 3
game3 1
game4 1
game4 2
我不知道是否有某种方法可以使用动物园&#39;库和na.locf或者如果我需要编写for循环或某种函数。
答案 0 :(得分:3)
使用dplyr group和cumsum:
library(dplyr)
df1 %>%
group_by(game) %>%
mutate(shot_number_new = cumsum(is.na(shot_number)) + 1)
# Source: local data frame [8 x 3]
# Groups: game [4]
#
# game shot_number shot_number_new
# <fctr> <dbl> <dbl>
# 1 game1 1 1
# 2 game1 NA 2
# 3 game2 1 1
# 4 game2 NA 2
# 5 game2 NA 3
# 6 game3 1 1
# 7 game4 1 1
# 8 game4 NA 2
答案 1 :(得分:0)
您可以使用SELECT *
FROM your_table
WHERE CAST(ID AS VARCHAR(20)) LIKE '%35%';
和group_by()
而无需明确使用原始row_number()
列:
shot_number