【问题标题】:Recode factor based on values from a string根据字符串中的值重新编码因子
【发布时间】:2022-11-02 01:10:19
【问题描述】:

我有一个(非常)大的数据集,它是从服务器导入的,没有任何格式。格式已在文本文件中提供给我。假设我在数据框中有一个变量,有什么方法可以将其格式化为字符串中定义的级别的因子。

举个例子,一个数据帧df,它有一个变量value,可以取1、2或3,应该按照字符串format中的定义进行编码:

format <- "
    1 = 'Declined'
    2 = 'Registered'
    3 = 'Randomised'
"

df %>%
  mutate(value = as.factor(value) %>%
           fct_recode(format))

【问题讨论】:

    标签: r forcats


    【解决方案1】:

    我们可能会使用

    library(dplyr)
    library(forcats)
    format <- c(Declined = "1", Registered = "2", Randomised = "3")
    df <- df %>% 
        mutate(value = fct_recode(value, !!!format))
    

    数据

    df <- data.frame(value = factor(c(1, 2, 3, 1, 2)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多