help
February 15, 2023, 1:33am
1
dat1 %>%
rowwise() %>%
mutate(total_score = sum(c_across(contains("score"))))
I have the above code that allows me to sum all columns that contain the word score in the variable name
how do I do rowwise sum that allows me to sum all my columns except for the ones titled "dog", "monkey" "Ali". this would bevery helpful to know thank you sooo much
FJCC
February 15, 2023, 1:55am
2
Here is one way to do that.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
DF <- data.frame(A = 1:3, dog = 1:3, B = 1:3, C = 1:3, monkey = 1:3, Ali = 1:3, D = 1:3)
DF |> rowwise() |> mutate(Total = sum(c_across(!matches(c('dog','monkey','Ali')))))
#> # A tibble: 3 × 8
#> # Rowwise:
#> A dog B C monkey Ali D Total
#> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 1 1 1 1 1 1 1 4
#> 2 2 2 2 2 2 2 2 8
#> 3 3 3 3 3 3 3 3 12
Created on 2023-02-14 with reprex v2.0.2
2 Likes
help
February 15, 2023, 2:38am
3
thank u so much!!! is there a way to add, Na.Rm = TRUE to the sum and it still works?
FJCC
February 15, 2023, 2:49am
4
Sure.
DF <- data.frame(A = 1:3, dog = 1:3, B = 1:3, C = 1:3, monkey = 1:3, Ali = 1:3, D = 1:3)
DF |> rowwise() |> mutate(Total = sum(c_across(!matches(c('dog','monkey','Ali'))), na.rm = TRUE))
system
Closed
March 29, 2023, 2:49am
5
This topic was automatically closed 42 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.