我有以下数据帧:
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 回答
如果它不是您项目中的要求,请尽量避免
factor
.character
更容易处理,并作为factor
存储为内存效率 . 我只使用因子来绘制或需要一些特定的排序顺序而不是按字母顺序排列 .这在过去是不同的,这解释了为什么字符串强制到
factor
仍然是许多函数中的默认值 . 您必须使用显式参数stringsAsFactors = FALSE
调用read.csv
或data.frame
以避免这种情况 .最近的R包如
data.table
或来自Hadley的tidyverse(tibble
)的R包从不强制输入 .但是如果你需要
factor
,你可以关注@Alistaire 's advice and use Hadley' sforecats
包 .更改因子级别的tidyverse方式是
forcats::fct_recode
,它维护因子类型但更改任何指定的级别: