[英]R - Create new column differentially based on another column
I have the following dataset:我有以下数据集:
ID year start_year
a 1 1
a 2 1
a 3 1
b 1 2
b 2 2
b 3 2
c 1 3
c 2 3
c 3 3
And I want to create a new dummy column present
that, for each ID is, 1-1-1 if start_year is 1, is 0-1-1 if start_year is 2, and is 0-0-1 if start_year is 3. My goal is to get the following table:我想创建一个新的虚拟列
present
对于每个 ID,如果 start_year 为 1,则为 1-1-1,如果 start_year 为 2,则为 0-1-1,如果 start_year 为 3,则为 0-0-1。我的目标是获得下表:
ID year start_year present
a 1 1 1
a 2 1 1
a 3 1 1
b 1 2 0
b 2 2 1
b 3 2 1
c 1 3 0
c 2 3 0
c 3 3 1
I guess this should be fairly easy for most of you, but I'm really stuck.我想这对你们大多数人来说应该相当容易,但我真的被困住了。 Many thanks for your help!
非常感谢您的帮助!
Easier option is to create a key/value list
and then subset the list
with the first
element of 'start_year' for each 'ID' (assuming there are only 3 elements per group)更简单的选择是创建一个键/值
list
,然后使用每个“ID”的“start_year”的first
元素对list
进行子集化(假设每组只有 3 个元素)
library(dplyr)
lst1 <- list(`1` = c(1, 1, 1), `2` = c(0, 1, 1), `3` = c(0, 0, 1))
df1 %>%
group_by(ID) %>%
mutate(present = lst1[[as.character(first(start_year))]]) %>%
ungroup
-output -输出
# A tibble: 9 × 4
ID year start_year present
<chr> <int> <int> <dbl>
1 a 1 1 1
2 a 2 1 1
3 a 3 1 1
4 b 1 2 0
5 b 2 2 1
6 b 3 2 1
7 c 1 3 0
8 c 2 3 0
9 c 3 3 1
df1 <- structure(list(ID = c("a", "a", "a", "b", "b", "b", "c", "c",
"c"), year = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), start_year = c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA,
-9L))
A possible approach:一种可能的方法:
library(tidyverse)
df <- tribble(
~ID, ~year, ~start_year,
"a", 1, 1,
"a", 2, 1,
"a", 3, 1,
"b", 1, 2,
"b", 2, 2,
"b", 3, 2,
"c", 1, 3,
"c", 2, 3,
"c", 3, 3
)
df |> mutate(present = if_else(start_year <= year, 1, 0))
#> # A tibble: 9 × 4
#> ID year start_year present
#> <chr> <dbl> <dbl> <dbl>
#> 1 a 1 1 1
#> 2 a 2 1 1
#> 3 a 3 1 1
#> 4 b 1 2 0
#> 5 b 2 2 1
#> 6 b 3 2 1
#> 7 c 1 3 0
#> 8 c 2 3 0
#> 9 c 3 3 1
Created on 2022-05-27 by the reprex package (v2.0.1)由reprex package (v2.0.1) 创建于 2022-05-27
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.