您现在的位置是:首页 > 电脑 > 

将因子级别更改为列的自定义顺序(change factor levels to custom order of a column)

2025-07-20 06:44:53
将因子级别更改为列的自定义顺序(change factor levels to custom order of a column) 我有一个如下数据框 > data = data.frame(name = c('Mike', 'Tony', 'Carol', 'Tim', 'Joe'), veh = c('car', 'bike', 'car', 'c
将因子级别更改为列的自定义顺序(change factor levels to custom order of a column)

我有一个如下数据框

> data = data.frame(name = c('Mike', 'Tony', 'Carol', 'Tim', 'Joe'), veh = c('car', 'bike', 'car', 'car', 'cycle') ) > data name veh 1 Mike car 2 Tony bike Carol car 4 Tim car 5 Joe cycle > str(data$name) Factor w/ 5 levels "Carol","Joe",..: 5 1 4 2 > str(data$veh) Factor w/ levels "bike","car","cycle": 2 1 2 2 > levels(data$veh) [1] "bike" "car" "cycle"

默认情况下,因子级别设置为1表示自行车,2表示汽车,表示循环。 我需要将因子水平改为1为汽车,2为循环,为自行车 - 我该如何解决这个问题?

I have a data frame like below

> data = data.frame(name = c('Mike', 'Tony', 'Carol', 'Tim', 'Joe'), veh = c('car', 'bike', 'car', 'car', 'cycle') ) > data name veh 1 Mike car 2 Tony bike Carol car 4 Tim car 5 Joe cycle > str(data$name) Factor w/ 5 levels "Carol","Joe",..: 5 1 4 2 > str(data$veh) Factor w/ levels "bike","car","cycle": 2 1 2 2 > levels(data$veh) [1] "bike" "car" "cycle"

By default the factor levels are set as 1 for bike, 2 for car, for cycle. I need to change factor levels as 1 for car, 2 for cycle and for bike - how do I go about this ?

最满意答案

tidyverse / forcats解决方案没有任何问题,但base-R解决方案是使用factor()和所需顺序指定的levels参数:

data$veh <- factor(data$veh, levels=c("car","cycle","bike"))

与普遍看法相反,在这种情况下, ordered=TRUE通常不是必需的(即使普通因子也有排序), 除非您特别想将焦点变量视为序数变量(在这种情况下R将使用正交多项式对比,而不是比处理对比,默认情况下),或者希望能够在变量上使用比较运算符(例如veh > "car" ); 如果你不确定,默认(普通)因素可能很好。

othing wrong with the tidyverse/forcats solution, but the base-R solution is to use factor() with the levels argument specified in the desired order:

data$veh <- factor(data$veh, levels=c("car","cycle","bike"))

Contrary to common belief, ordered=TRUE isn't typically necessary in this case (even ordinary factors have an ordering), unless you specifically want to treat the focal variable as an ordinal variable (in which case R will use orthogonal polynomial contrasts, rather than treatment contrasts, by default), or want to be able to use comparison operators on the variable (e.g. veh > "car"); if you're not sure, the default (ordinary) factors are probably fine.

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/diannao/654077.html

相关标签:无
上传时间: 2023-07-28 12:52:30
留言与评论(共有 9 条评论)
本站网友 自制美白祛斑面膜
21分钟前 发表
"car"
本站网友 有一种爱叫放手
23分钟前 发表
'Joe')
本站网友 扭扭捏捏的意思
3分钟前 发表
or want to be able to use comparison operators on the variable (e.g. veh > "car"); if you're not sure
本站网友 脑瘫儿童
20分钟前 发表
"cycle"
本站网友 中国退休年龄
6分钟前 发表
而不是比处理对比
本站网友 h2o官网
9分钟前 发表
默认情况下)
本站网友 与卓越同行
11分钟前 发表
或者希望能够在变量上使用比较运算符(例如veh > "car" ); 如果你不确定
本站网友 下颌角肥大矫正术
4分钟前 发表
'car'