【问题标题】:How to use %in% to make string replacements (str_replace) in R如何使用 %in% 在 R 中进行字符串替换(str_replace)
【发布时间】:2018-10-28 19:36:09
【问题描述】:

我正在尝试找到一种优雅的方式来使用 %in% 和 str_replace() 来清理性别。我知道我可以使用 regx() 来做同样的事情,但我正在寻找解决同样问题的替代方法。

我的代码是:

sex <- c("Male","girl","boy", "female")
male <- c("Male", "boy")
female <- c("girl", "female")

我知道这段代码不正确,但说明了我正在尝试做的事情

str_replace(sex, sex %in% male, "M")
str_replace(sex, sex %in% female, "F")

有什么建议吗?

【问题讨论】:

    标签: r str-replace


    【解决方案1】:

    你可以用replace而不是str_replace来做到这一点:

    sex <- c("Male","girl","boy", "female")
    male <- c("Male", "boy")
    female <- c("girl", "female")
    
    sex <- replace(sex, which(sex %in% male), "M")
    sex <- replace(sex, which(sex %in% female), "F")
    sex
    #> [1] "M" "F" "M" "F"
    

    reprex package (v0.2.1) 于 2018 年 10 月 28 日创建

    【讨论】:

    • 这么简单!!谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多