Reputation: 867
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?
Upvotes: 0
Views: 286
Reputation: 37641
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.
Upvotes: 1