Home > front end >  where function in sum for row wise calculation
where function in sum for row wise calculation

Time:09-30

i trying the below code where i am trying to get the row wise sum of a, b and c teams which are all numeric except for the team_league which is character, excluding this character variable i would like to derive the sum of numeric variables into a new variable league_points

to select the numeric variables i am using where(is.numeric) but it is not working, any thoughts

vital1 <- data.frame(a_team=c(1:3), b_team=c(2:4),team_league=c('dd','ee','ff'),c_team=c(5,9,1)) %>%
  rowwise() %>% 
  mutate(league_points=sum(where(is.numeric))
         )

CodePudding user response:

We can use where within c_across

library(dplyr)
data.frame(a_team=c(1:3), b_team=c(2:4),
      team_league=c('dd','ee','ff'),c_team=c(5,9,1)) %>%
   rowwise() %>%
   mutate(league_points = sum(c_across(where(is.numeric)), na.rm = TRUE)) %>%
   ungroup

-output

# A tibble: 3 × 5
  a_team b_team team_league c_team league_points
   <int>  <int> <chr>        <dbl>         <dbl>
1      1      2 dd               5             8
2      2      3 ee               9            14
3      3      4 ff               1             8

rowwise would be slow. Here, a vectorized function is already available i.e. rowSums

data.frame(a_team=c(1:3), b_team=c(2:4),
      team_league=c('dd','ee','ff'),c_team=c(5,9,1)) %>%
   mutate(league_points = rowSums(across(where(is.numeric)), na.rm = TRUE))

-output

   a_team b_team team_league c_team league_points
1      1      2          dd      5             8
2      2      3          ee      9            14
3      3      4          ff      1             8
  •  Tags:  
  • r
  • Related