# Feed Varlist into Calculation

#### hlsmith

##### Not a robit
I have a dataset which I want to add a new variable (column) based on a calculation of existing variables in the set. But I want to repeat the process for eight variables and I AM hoping to do it in one step. So I would feed in a varlist into the line of code and generate the 8 new terms. See following where I run it twice, I would collapse this into one statement for the eight vars.

Code:
#FOR BEEF#
Food_3$Beef = (((((((Food_3$IM_Weekly_serving_2
* Food_3$IM_Attendance_2) + Food_3$Peds_Monthly_serving_2
* Food_3$Peds_Attendance_2)) *Food_3$beef)
/Food_3$kg_oz_conversion_2) *Food_3$Serving_conversion_2)
/Food_3$Passenger_Vehicle_2) #FOR LAMB# Food_3$Lamb = (((((((Food_3$IM_Weekly_serving_2 * Food_3$IM_Attendance_2)
+ Food_3$Peds_Monthly_serving_2 * Food_3$Peds_Attendance_2))
*Food_3$lamb) /Food_3$kg_oz_conversion_2)
*Food_3$Serving_conversion_2) /Food_3$Passenger_Vehicle_2)
End result would be the addition of these two variables (Beef and Lamb) into the dataset Food_3.

Last edited:

#### Dason

Code:
myfun <- function(x){
(((((((Food_3$IM_Weekly_serving_2 * Food_3$IM_Attendance_2)
+ Food_3$Peds_Monthly_serving_2 * Food_3$Peds_Attendance_2))
*x)
/Food_3$kg_oz_conversion_2) *Food_3$Serving_conversion_2)
/Food_3$Passenger_Vehicle_2) } Food_3$Beef <- myfun(Food_3$beef) Food_3$Lamb <- myfun(Food_3\$lamb)
Improvements could be made but that seems to do what you want?

I did that on my phone so apologies for lack of decent formatting

#### hlsmith

##### Not a robit
Thanks.

I'll check it out in morning. I was thinking there was an *apply approach or way to feed in a list. In SAS i would feed a varlist. I usually get intimidated writing functions since I am inexperienced and never have enough time.

#tested and the code snippet works.

Last edited: