Is there a way to apply loops to multiply across various columns in a dataframe?
I have two data frames, one of them is prices and one is quantities.
They each have five years in them: 2013:2017.
So, I would like to divide
vector1 <- prices[,1] / quantities[,1]
vector2 <- prices[,2] / quantities[,2]
etc...
Is there a way to do this in a loop so my code can be more efficient?
Also, I have a data frame with 22 rows. I would like to divide the 21 upper rows to the row at the bottom for every column:
first <- df[,1] / df[22,1]
second <- df[,2] / df[22,2]
etc..
Is this something that can be implemented in a loop as well?
Here are some solutions to your problems. Neither one returns vectors. The first one returns a data frame that is the result of element by element division of two data frame. The second one returns a list of vectors that results from dividing each column by its last element.
I had a similar question.
This works across columns.
I'm not sure about loops etc..
DF1 <- data.frame(A = 1:5, B = 11:15, C = 21:25)
#### USE ROWWISE TO WORK ACROSS COLUMNS ####
DF1 <- DF1 %>%
rowwise() %>%
mutate(
SUM = sum(c(A,B,C), na.rm = TRUE)
) %>%
ungroup()
### I WAS TOLD TO UNGOUP BUT DON'T KNOW WHY ###