【问题标题】:Use recode to clean data frame column使用重新编码清理数据框列
【发布时间】:2020-05-04 11:51:50
【问题描述】:

如何使用recode() 来“清理/剥离”数据框中列的某些部分?原始数据框如下所示:

df <- data.frame(duration = c("concentration, up to 2 minutes", "concentration, up to 4 minutes", "up to 6 hours"), name = c("Earth", "Water", "Fire"))

改进后的版本是这样的:

df <- data.frame(duration = c("2 minutes", "4 minutes", "6 hours"), name = c("Earth", "Water", "Fire"))

所以,我应该删除“concentration”和“up to”,或者使用recode函数将其替换为空字符串。

【问题讨论】:

    标签: r dataframe recode


    【解决方案1】:

    请使用dplyr::recode()strings::str_remove() 找到这两种解决方案。

    我的建议是也学习后者。这样,您将能够学习通过正则表达式转换字符串的更强大的方法。

    dplyr::recode() 的解决方案

    library(dplyr)
    #> 
    #> Attaching package: 'dplyr'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    df <- data.frame(duration = c("concentration, up to 2 minutes", 
                                  "concentration, up to 4 minutes", 
                                  "up to 6 hours"), 
                     name = c("Earth", "Water", "Fire"))
    
    df$duration = recode(df$duration, 
                         "concentration, up to 2 minutes" = "2 minutes",
                         "concentration, up to 4 minutes" = "4 minutes",
                         "up to 6 hours" = "6 hours" )
    df
    #>    duration  name
    #> 1 2 minutes Earth
    #> 2 4 minutes Water
    #> 3   6 hours  Fire
    

    reprex package (v0.3.0) 于 2020 年 5 月 4 日创建

    stringr::str_remove() 的解决方案

    library(stringr)
    df <- data.frame(duration = c("concentration, up to 2 minutes", 
                                  "concentration, up to 4 minutes", 
                                  "up to 6 hours"), 
                     name = c("Earth", "Water", "Fire"))
    
    
    df$duration = str_remove( df$duration, "^.*(?=\\d)")
    df
    #>    duration  name
    #> 1 2 minutes Earth
    #> 2 4 minutes Water
    #> 3   6 hours  Fire
    

    reprex package (v0.3.0) 于 2020 年 5 月 4 日创建

    【讨论】:

    • @Monique 我更新了我的答案。这就是您想要的,请将其标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多