首页 文章

dplyr在数据帧上变异.Label值,而不是引用

提问于
浏览
1

我有以下数据帧:

temp <- structure(list(ID = c("1234", "1223", "5555", "2344", "4567", "6543"), 
       Eat = structure(c(6L,1L, 5L, 2L, 3L, 4L), 
       .Label = c("", "Cabbage", "Carrot", "Lettuce", "Potato","Asparagus", "Mushroom", "Apple"), class = "factor")), 
      row.names = c(NA, 6L), class = "data.frame", .Names = c("ID", "Eat"))

我想注意每次吃什么都没有:

temp %>% mutate(Eat = ifelse(Eat != "" & !is.na(Eat), Eat, "Nothing!"))

然而,结果是Eat结构值的变异,:

ID      Eat
1 1234        6
2 1223 Nothing!
3 5555        5
4 2344        2
5 4567        3
6 6543        4

如何让.Labels进行制作:

ID      Eat
1 1234Asparagus
2 1223 Nothing!
3 5555   Potato
4 2344  Cabbage
5 4567   Carrot
6 6543  Lettuce

2 回答

  • 1

    如果它不是您项目中的要求,请尽量避免 factor . character 更容易处理,并作为 factor 存储为内存效率 . 我只使用因子来绘制或需要一些特定的排序顺序而不是按字母顺序排列 .

    “... R有一个全局字符串池 . 这意味着每个唯一的字符串只存储在一个地方,因此字符向量占用的内存比你想象的要少”(Hadley Wickham,Advanced R)

    这在过去是不同的,这解释了为什么字符串强制到 factor 仍然是许多函数中的默认值 . 您必须使用显式参数 stringsAsFactors = FALSE 调用 read.csvdata.frame 以避免这种情况 .

    最近的R包如 data.table 或来自Hadley的tidyverse( tibble )的R包从不强制输入 .

    但是如果你需要 factor ,你可以关注@Alistaire 's advice and use Hadley' s forecats 包 .

  • 2

    更改因子级别的tidyverse方式是 forcats::fct_recode ,它维护因子类型但更改任何指定的级别:

    library(forcats)
    
    temp %>% mutate(Eat = fct_recode(Eat, 'Nothing!' = ''))
    
    ##     ID       Eat
    ## 1 1234 Asparagus
    ## 2 1223  Nothing!
    ## 3 5555    Potato
    ## 4 2344   Cabbage
    ## 5 4567    Carrot
    ## 6 6543   Lettuce
    

相关问题