I've written a simple code to add two columns (A_Purchase_Freq and T_A_Expenditure) to my dataset WM_Purchased_1:
WM_Purchased_1 <- WM_Purchased_1 %>%
mutate(A_Purchase_Freq =
ifelse(utfoodb=="Daily", tfoodb*30*mfoodbly,
ifelse(utfoodb=="Weekly", tfoodb*4*mfoodbly,
ifelse(utfoodb=="Monthly", tfoodb*1*mfoodbly,
ifelse(utfoodb=="Quarterly", tfoodb*4,
ifelse(utfoodb=="Bi-Annually", tfoodb*2,
ifelse(utfoodb=="Annually", tfoodb*1, "NA"))))))) %>%
mutate(A_Purchase_Freq= as.numeric(A_Purchase_Freq)) %>%
mutate(T_A_Expenditure = A_Purchase_Freq * cfoodb)
I'd now like to apply the same function to 3 more datasets (WM_Purchased_2
, WM_Purchased_3
, WM_Purchased_4
).
So far, I've created the function f1:
f1 <- function(dat) {
dat<- dat %>%
mutate(A_Purchase_Freq =
ifelse(utfoodb=="Daily", tfoodb*30*mfoodbly,
ifelse(utfoodb=="Weekly", tfoodb*4*mfoodbly,
ifelse(utfoodb=="Monthly", tfoodb*1*mfoodbly,
ifelse(utfoodb=="Quarterly", tfoodb*4,
ifelse(utfoodb=="Bi-Annually", tfoodb*2,
ifelse(utfoodb=="Annually", tfoodb*1, "NA"))))))) %>%
mutate(A_Purchase_Freq= as.numeric(A_Purchase_Freq)) %>%
mutate(T_A_Expenditure = A_Purchase_Freq * cfoodb)
}
I then created a list of my data frames using list()
, and attempted to apply my function to the list use lapply
:
dflist<- list(WM_Purchased_2, WM_Purchased_3, WM_Purchased_4)
lapply(dflist, f1)
But I can't for the life of me figure out how to add the columns to the original data frames, rather than just returning the data in the console or as a list.
Any help would be appreciated! (Sorry I can't share the datasets)
Edit: Here's a reproducible example:
m1 <- as.data.frame(matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4])))
m2 <- as.data.frame(matrix(4:15, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4])))
listdf<- list(m1, m2)
f1 <- function(dat) {
dat<- dat %>%
mutate(E = C* D)
}
lapply(listdf, f1)
So in short I want column E added to data frames m1 and m2, not returned in the console.