创建一个过滤器变量,以指示时间顺序值在r中可用
我有学生分数,有些学生按时间顺序取多个分数。这是我的示例数据集创建一个过滤器变量,以指示时间顺序值在r中可用,r,filter,R,Filter,我有学生分数,有些学生按时间顺序取多个分数。这是我的示例数据集 df <- data.frame( id = c(1,2,2,3,4,5,5,6), time = c(1,1,2,1,1,1,2,1), score = c(15,16,18,19,22,29,19,52)) > df id time score 1 1 1 15 2 2 1 16 3 2 2 18 4 3
df <- data.frame(
id = c(1,2,2,3,4,5,5,6),
time = c(1,1,2,1,1,1,2,1),
score = c(15,16,18,19,22,29,19,52))
> df
id time score
1 1 1 15
2 2 1 16
3 2 2 18
4 3 1 19
5 4 1 22
6 5 1 29
7 5 2 19
8 6 1 52
有人有主意吗
谢谢 这是否有效:
library(dplyr)
df %>% mutate(score1 = case_when(time == 1 ~ 1, TRUE ~ 0),
score2 = case_when(time == 2 ~ 1, TRUE ~ 0))
id time score score1 score2
1 1 1 15 1 0
2 2 1 16 1 0
3 2 2 18 0 1
4 3 1 19 1 0
5 4 1 22 1 0
6 5 1 29 1 0
7 5 2 19 0 1
8 6 1 52 1 0
library(dplyr)
df %>% mutate(score1 = case_when(time == 1 ~ 1, TRUE ~ 0),
score2 = case_when(time == 2 ~ 1, TRUE ~ 0))
id time score score1 score2
1 1 1 15 1 0
2 2 1 16 1 0
3 2 2 18 0 1
4 3 1 19 1 0
5 4 1 22 1 0
6 5 1 29 1 0
7 5 2 19 0 1
8 6 1 52 1 0