使用 dplyr mutate 改变因子水平 [英] Changing factor levels with dplyr mutate

查看:29
本文介绍了使用 dplyr mutate 改变因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能很简单,我觉得问起来很愚蠢.我想使用 mutate 更改数据框中因子的级别.简单例子:

This is probably simple and I feel stupid for asking. I want to change the levels of a factor in a data frame, using mutate. Simple example:

library("dplyr")
dat <- data.frame(x = factor("A"), y = 1)
mutate(dat,levels(x) = "B")

我明白了:

Error: Unexpected '=' in "mutate(dat,levels(x) ="

为什么这不起作用?如何使用 mutate 更改因子水平?

Why is this not working? How can I change factor levels with mutate?

推荐答案

使用 forcats 包来自 tidyverse 这也很简单.

With the forcats package from the tidyverse this is easy, too.

mutate(dat, x = fct_recode(x, "B" = "A"))

这篇关于使用 dplyr mutate 改变因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆