gpt4 book ai didi

r - 如何根据另一列中值的第一个字符填充一列?

转载 作者:行者123 更新时间:2023-12-01 23:04:02 25 4
gpt4 key购买 nike

我需要添加一个标记为 Cohort 的因子列,并根据 ID 的第一个字母用 1 或 2 填充它。如果 A 则 1,如果 B 则 2。我如何使用 dplyr 完成此操作?谢谢

collars <- collars %>%
mutate(Cohort = ?)

structure(list(Id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = c("A628", "A629", "A630", "A631", "A632", "A633",
"A634", "A635", "A636", "A637", "A82117", "A82118", "A82119",
"A82120", "A82121", "A82122", "A82123", "A82124", "A82125", "A82126",
"A82127", "A82129", "A82130", "A82131", "A82132", "A82133", "A82134",
"A82135", "A82136", "A82137", "A82138", "A82139", "A82140", "A82141",
"A82142", "A82143", "A82144", "A82145", "A82146", "B628", "B629",
"B630", "B631", "B632", "B633", "B634", "B635", "B636", "B637",
"B82117", "B82118", "B82119", "B82120", "B82121", "B82122", "B82123",
"B82126", "B82127", "B82128", "B82129", "B82130", "B82131", "B82132",
"B82133", "B82135", "B82136", "B82137", "B82138", "B82139", "B82140",
"B82141", "B82143", "B82145"), class = "factor"), DateTime = structure(c(1557401400,
1557403200, 1557405000, 1557406800, 1557408600, 1557410400, 1557417600,
1557419400, 1557421200, 1557423000), class = c("POSIXct", "POSIXt"
), tzone = "CST6CDT")), row.names = c(NA, 10L), class = "data.frame")

最佳答案

我认为以下解决方案可能对您有所帮助:

library(dplyr)

df %>%
rowwise() %>%
mutate(cohort = case_when(
substr(Id, 1, 1) == "A" ~ 1,
substr(Id, 1, 1) == "B" ~ 2,
TRUE ~ NA_real_
))

Id DateTime cohort
1 A628 2019-05-09 06:30:00 1
2 A628 2019-05-09 07:00:00 1
3 A628 2019-05-09 07:30:00 1
4 A628 2019-05-09 08:00:00 1
5 A628 2019-05-09 08:30:00 1
6 A628 2019-05-09 09:00:00 1
7 A628 2019-05-09 11:00:00 1
8 A628 2019-05-09 11:30:00 1
9 A628 2019-05-09 12:00:00 1
10 A628 2019-05-09 12:30:00 1

关于r - 如何根据另一列中值的第一个字符填充一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71313315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com