Home > Software engineering >  Divide each row by the rowvalue of a certain column
Divide each row by the rowvalue of a certain column

Time:10-25

I want to divide all rows based on the rowvalue by a certain column (col4), for each row.Any suggestion of how to do it? Thanks!

# declaring dataframe
data_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), 
                         col3 = c(9,12,15), col4 = c(1,2,3))



    data_frame
col1 col2 col3 col4
2    4    9    1
4    6   12    2
6    8   15    3

Wanted output:

   col1 col2  col3 col4
    2    4     9    1
    2    3     6    1
    2    2.67  5    1

CodePudding user response:

library(dplyr)
# #Data
data_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), col3 = c(9,12,15), col4 = c(1,2,3))

data_frame %>% 
  rowwise() %>% 
  mutate(across(everything(), ~ . / col4))
# A tibble: 3 x 4
# Rowwise: 
#   col1  col2  col3  col4
#  <dbl> <dbl> <dbl> <dbl>
#1     2  4        9     1
#2     2  3        6     1
#3     2  2.67     5     1

CodePudding user response:

rowwise is not needed:

library(tidyverse)

data_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), 
                         col3 = c(9,12,15), col4 = c(1,2,3))

data_frame %>% 
  mutate(across(everything(), ~ ./col4))
#>   col1     col2 col3 col4
#> 1    2 4.000000    9    1
#> 2    2 3.000000    6    1
#> 3    2 2.666667    5    1

CodePudding user response:

In base R:

data_frame[,1:4] <- sapply(data_frame, function(x) x/data_frame$col4)

data_frame
  col1     col2 col3 col4
1    2 4.000000    9    1
2    2 3.000000    6    1
3    2 2.666667    5    1
  •  Tags:  
  • r
  • Related