gpt4 book ai didi

r - 在 R 中使用 dplyr::if_else 条件创建新列

转载 作者:行者123 更新时间:2023-12-02 03:19:41 26 4
gpt4 key购买 nike

我编写了以下代码来根据上一列的某些条件创建一个新列。我相信我需要添加一个附加条件来保留以前的值。

BP2018_spread <- BP2018_spread  %>%
dplyr :: mutate(Period_Type = if_else(grepl("QTD",BP2018_spread$Month), 'QTD', if_else(grepl("YTD",BP2018_spread$Month),'YTD', 'NA')))

Current Output:
Month Period_Type
<chr> <chr>
1 " Apr" NA
2 " Apr QTD" QTD
3 " Apr YTD" YTD
4 " Aug" NA
5 " Aug QTD" QTD
6 " Aug YTD" YTD
7 " Dec" NA
8 " Dec QTD" QTD
9 " Dec YTD" YTD
10 " Feb" NA


Desired Output:
Month Period_Type
<chr> <chr>
1 " Apr" Apr
2 " Apr QTD" QTD
3 " Apr YTD" YTD
4 " Aug" Aug
5 " Aug QTD" QTD
6 " Aug YTD" YTD
7 " Dec" Dec
8 " Dec QTD" QTD
9 " Dec YTD" YTD
10 " Feb" Feb

或者

Desired Output:
Month Period_Type
<chr> <chr>
1 " Apr" MTD
2 " Apr QTD" QTD
3 " Apr YTD" YTD
4 " Aug" MTD
5 " Aug QTD" QTD
6 " Aug YTD" YTD
7 " Dec" MTD
8 " Dec QTD" QTD
9 " Dec YTD" YTD
10 " Feb" MTD

最佳答案

你可以试试吗

    BP2018_spread <- BP2018_spread  %>%
dplyr::mutate(Period_Type = ifelse(grepl("QTD", Month), 'QTD',
ifelse(grepl("YTD", Month),'YTD', 'MTD')))

关于r - 在 R 中使用 dplyr::if_else 条件创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167791/

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