Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Ones with Zeros and Zeros with Ones in a dataframe [duplicate]

I have a dataframe df. I would like to replace all zeros with ones and all ones with zeros in the dataframe. Or in general, if I have to find some value (like one) and replace the value with something else, what's the best approach?

  a b
1 1 0
2 0 1
3 1 0
4 0 0
like image 247
yome Avatar asked Sep 05 '25 03:09

yome


2 Answers

A code golf would be to negate the dataset and use +

+(!df)
#  a b
#1 0 1
#2 1 0
#3 0 1
#4 1 1
like image 147
akrun Avatar answered Sep 07 '25 20:09

akrun


mydata=data.frame(a=c(1,0,1,0),b=c(0,1,0,0));
psych::reverse.code(c(-1,-1),mydata)
like image 26
Dimitrios Zacharatos Avatar answered Sep 07 '25 21:09

Dimitrios Zacharatos