0

How can a vector of items be passed to single argument in function using R?

I have the below function that changes the values of variables in a data frame.

DF:

df <- read.table(text=" PROD var1 var2 1 1 0 2 0 0 3 0 0 1 1 0 2 0 0 3 0 0 ", header=T) 

Function

Chg.var.df.t <- function(data, prod, vars, numvar, lvl){ if(numvar==2 & lvl==1){ data[data$PROD == prod, vars] <- 1 data[data$PROD == prod, vars] <- 0} if(numvar==2 & lvl == 2){ data[data$PROD == prod, vars] <- 0 data[data$PROD == prod, vars] <- 1} if(numvar==2 & lvl == 3){ data[data$PROD == prod, vars] <- -1 data[data$PROD == prod, vars] <- -1} return(data) } Chg.var.df.t(df, 1, c("var1", "var2"), 2, 1) 

Result

 PROD var1 var2 1 1 0 0 2 2 0 0 3 3 0 0 4 1 0 0 5 2 0 0 6 3 0 0 

So, I guess each variable is passed to each data[data$PROD == prod, vars].

My desired result is

 PROD var1 var2 1 1 1 0 2 2 0 0 3 3 0 0 4 1 1 0 5 2 0 0 6 3 0 0 

Instead of two var[i] arguments in the function, I am trying to figure out how to specify them as a vector in a single argument like c("var1", "var2"). What do I need to change in the function to accomplish this?

1 Answer 1

1
 Chg.var.df <- function(data, prod, vars){ data[data$PROD == prod, vars] <- -1 return(data) } 

and pass in a list of variables to the function.

Sign up to request clarification or add additional context in comments.

6 Comments

will that still work if var1 and var2 have different values? E.g. data[data$PROD == prod, var1] <- -1 data[data$PROD == prod, var2] <- 0
Yes, you can do something like V = c(var1, var2) Chg.var.df(data, prod, V)
Shouldn't this be data[data$PROD == prod, vars] <- c(-1, 0) or something?
I was assuming that he was changing them all to -1 based on his example.
G5W that was way easier than I expected. Thank you.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.