Calculate accross columns within a data frame

Hi,

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?

Have a nice day everyone!

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.

DF1 <- data.frame(A = 1:5, B = 11:15, C = 21:25)
DF2 <- data.frame(X = 2:6, Y = 12:16, Z = 22:26)
DF1/DF2
#>           A         B         C
#> 1 0.5000000 0.9166667 0.9545455
#> 2 0.6666667 0.9230769 0.9565217
#> 3 0.7500000 0.9285714 0.9583333
#> 4 0.8000000 0.9333333 0.9600000
#> 5 0.8333333 0.9375000 0.9615385

DivCol <-  function(Col) Col/Col[length(Col)]
library(purrr)
map(DF1,  ~DivCol(.))
#> $A
#> [1] 0.2 0.4 0.6 0.8 1.0
#> 
#> $B
#> [1] 0.7333333 0.8000000 0.8666667 0.9333333 1.0000000
#> 
#> $C
#> [1] 0.84 0.88 0.92 0.96 1.00

Created on 2020-04-24 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

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 ###

Created on 2020-04-24 by the reprex package (v0.3.0)

Cheers,
Jason the #rstatsnewbie