【问题标题】:Is there any R function to replace "part" of factor in column?是否有任何 R 函数来替换列中因子的“部分”?
【发布时间】:2021-06-08 11:01:38
【问题描述】:

‚¬0 €100K €105K
Ø 10K €110K

上面是数据框中列的头部。这是一个因素。我想从完整列中删除 'â¬' 这部分。但是在尝试使用替换函数替换后,它正在更改为字符并将值提供为“0”、“100K”、“105k”、“10k” ","110k"。帮我解决这个问题。

fb$Wage = sub('€','',fb$Wage)
fb$Wage

【问题讨论】:

  • 重新转换为因子:factor(sub('€','',fb$Wage)).

标签: r dataframe character data-cleaning substitution


【解决方案1】:

更改levels 而不是factor 的值:

levels(x) <- sub('€','', levels(x))
x
#[1] 0    100K 105K 10K  110K
#Levels: 0 100K 105K 10K 110K

数据:

x <- factor(c("€0", "€100K", "€105K", "€10K", "€110K"))

【讨论】:

    【解决方案2】:

    fct_recode 的选项

    library(forcats)
    library(stringr)
    fct_recode(x, !!!setNames(levels(x), str_remove_all(levels(x), "[^[:ascii:]]+")))
    #[1] 0    100K 105K 10K  110K
    #Levels: 0 100K 105K 10K 110K
    

    数据

    x <- factor(c("€0", "€100K", "€105K", "€10K", "€110K"))
    

    【讨论】:

    • 如果我也想删除 k 怎么办? @akrun
    • @SaiNikhilKataru 这很容易,即fct_recode(x, !!!setNames(levels(x), str_remove_all(levels(x), "\\D+")))#[1] 0 100 105 10 110 Levels: 0 100 105 10 110
    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2020-07-21
    • 2019-07-26
    • 1970-01-01
    • 2014-05-14
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多