yzhao
yzhao

Reputation: 47

write r function to modify value in data frame

I have a set a variables say Var1, Var2 to Varn. They all take three possible values 0, 1, and 2. I want to replace all 2 as 1

like so
df$Var1[df$Var1 >= 1] <- 1

This does the job. But when I try to write a function to do this

MakeBinary <- function(varName dfName){dfName$varName[dfName$varNAme > = 1] <- 1}

and use this function like:

MakeBinary(Var2, df)

I got an error message: Error in $<-.data.frame(*tmp*, "varName", value = numeric(0)) : replacement has 0 rows, data has 512.

I just want to know why I got this message. Thanks. My sample size is 512.

Upvotes: 1

Views: 1116

Answers (1)

akrun
akrun

Reputation: 887118

If we are passing column name as string, then use [[ instead of $ and return the dataset

MakeBinary <- function(varName, dfName){
     dfName[[varName]][dfName[[varName]] >= 1] <- 1
   dfName
   }

MakeBinary("Var2", df)

example with mtcars

MakeBinary("carb", head(mtcars))
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    1
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    1
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    1
#Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Unquoted arguments for variable names can be passed as well, but it needs to be converted to string

MakeBinary <- function(varName, dfName){
     varName <- deparse(substitute(varName))
     dfName[[varName]][dfName[[varName]] >= 1] <- 1
   dfName
   }

MakeBinary(Var2, df)

Using a reproducible example with mtcars

MakeBinary(carb, head(mtcars))
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    1
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    1
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    1
#Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Upvotes: 2

Related Questions