Rajesh Gangwar Rajesh Gangwar - 2 years ago 87
R Question

Update Values in R values greater than 0 to 1 in numeric columns

I have a data frame with 1:13 character columns and 14:176 numeric columns. i want to replace all values greater than 0 from 1 in numeric columns only.

i tried with:

HRtest1 <- cbind(HRtest[,1:13],
apply(HRtest[,14:176], 2, function(x) {replace(x, x>0, 1)}))

but this code is working only when i change my data frame to matrix and some of values are not updating(like 184.97965 is still there).

another code i tried with is:

HRtest1<- as.data.table(lapply(HRtest, function(x){replace(x, x >0,1)}))

but with this character columns also update to 1. please help me with this.

Answer Source

There are various ways to deal with this. But I would like a general scenario. The reason why the strings/characters are changing is because they are taken to be factors. Please ensure you change the class to characters :

 sapply(A, function(x) if(is.numeric(x)) replace(x,x>0,1) else x)

or you can just decide and go ahead and do:

A[,-(1:13)]=sapply(A[,-(1:13)],function(x) replace(x,x>0,1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download