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.

I have the following data

 solved_status
1            ABC
2            XYZ
3            ABC
4            MNP
5            XYZ
6            MNP

I have to change it to

   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}}

An error occurred-

 Error in rep(value, length.out = nrows) : attempt to replicate an object of type 'closure'

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)

Got an error again -

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?

maggs
  • 763
  • 2
  • 9
  • 15

2 Answers2

2

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)

or:

all$class <- c(0,1)[all$solved_status=="ABC" + 1L]

or:

all$class <- as.integer(all$solved_status=="ABC")

should work.

Jaap
  • 81,064
  • 34
  • 182
  • 193
1

Here is another option with recode

library(car)
recode(df1$solved_status, "'ABC'=1;else=0")
#[1] 1 0 1 0 0 0

The advantage of recode is that it can be used for factor, character columns and change it to any values.

Suppose, we have a factor vector

v1 <- factor(c("ABC", "ACD", "AFD", "ADR", "ABC", "ANC"))

and want to replace "ABC" with "a" and all others as "d"

recode(v1, "'ABC'= 'a'; else = 'd'")
#[1] a d d d a d
#Levels: a d

The output is a factor with levels automatically changed to 'a', 'd'.

akrun
  • 874,273
  • 37
  • 540
  • 662