更改列的因子值 [英] Change factor values of a column
本文介绍了更改列的因子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据同一数据帧的另一列solve_status列将值分配给Dataframe的新列。所有$ solve_status是3个标签-ABC,XYZ,MNP'的因子。我必须根据条件分配到0或1,如果(ABC)然后1 else 0。
I am trying to assign values to a new column of a Dataframe based on another column "solve_status" column of the same dataframe. all$solved_status is a factor with 3 labels -'ABC, XYZ, MNP'. I have to assign to 0 or 1 based on condition if (ABC) then 1 else 0.
我有以下数据
solved_status
1 ABC
2 XYZ
3 ABC
4 MNP
5 XYZ
6 MNP
我必须将其更改为
solved_status cls
1 ABC 1
2 XYZ 0
3 ABC 1
4 MNP 0
5 XYZ 0
6 MNP 0
pre$cls <- function(x){if(factor(pre$solved_status[x])=="ABC"){ pre$cls[x] = 1} else {pre[x,'cls'] =0}}
发生错误 -
Error in rep(value, length.out = nrows) : attempt to replicate an object of type 'closure'
然后我googled并将其更改为 -
then I googled and changed it to -
> func <- function(x){if(as.character(pre[x,'solved_status'])=="ABC"){ pre[x,'cls'] = 1} else { pre[x,'cls'] =0} }
> pre$cls = lapply(pre$solved_status,func)
再次出现错误 -
Error in Summary.factor(2L, na.rm = FALSE) : 'max' not meaningful for factors
我不知道我在哪里错了。有人可以纠正吗?
I don't know where I am getting wrong. Can someone please rectify?
推荐答案
没有必要编写自定义函数。您可以使用buildin R功能。或者:
There is no need to write a custom function. You can use buildin R-functionality. Either:
all$class <- ifelse(all$solved_status=="ABC", 1, 0)
或:
all$class <- c(0,1)[all$solved_status=="ABC" + 1L]
或:
all$class <- as.integer(all$solved_status=="ABC")
应该工作。
这篇关于更改列的因子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文