【问题标题】:Can I use mutate with conditions in R? [duplicate]我可以在 R 中使用带有条件的 mutate 吗? [复制]
【发布时间】:2020-07-04 04:23:41
【问题描述】:

假设我有以下数据框:

df <- data.frame(stock_code = c("600000", "300000", "000000"), 
                 stock_price = c(10.00, 11.00, 12.00))

我想在 stock_code 中添加一些字符,规则是:

  1. 如果stock_code的第一个数字是“6”,则在stock_code中添加“.XSHG”,如600000.XSHG
  2. 如果股票代码的第一个数字是“0”或“3”,则在股票代码中添加“.XSHE”,如300000.XSHE和000000.XSHE

我知道 str_sub 可能会有所帮助,但谁能告诉我如何使用 %&gt;% 在 tidyverse 中编码?

【问题讨论】:

    标签: r string tidyverse


    【解决方案1】:

    您可以使用grepl 查找模式,使用case_when 添加条件。

    library(dplyr)
    
    df %>%
      mutate(new_stock_code = case_when(
                grepl('^6', stock_code) ~ paste0(stock_code, '.XSHG'), 
                grepl('^[30]', stock_code) ~ paste0(stock_code, '.XSHE'), 
                TRUE ~ stock_code))
    
    
    #  stock_code stock_price new_stock_code
    #1     600000          10    600000.XSHG
    #2     300000          11    300000.XSHE
    #3     000000          12    000000.XSHE
    

    在基础 R 中,您可以使用嵌套的 ifelse

    transform(df, new_stock_code = ifelse(grepl('^6', stock_code), 
         paste0(stock_code, '.XSHG'), ifelse(grepl('^[30]', stock_code), 
         paste0(stock_code, '.XSHE'),stock_code)))
    

    【讨论】:

    • 两者都很好。编码 Golf,将 case_whenifelse 语句的 paste0 outside 带入,让它们返回 '.XSHG''.XSHE'"" 之一,然后将 paste0(stock_code, ...) 发送到整个case_when/ifelse
    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多