Home > OS >  Calculate amount of values ​in a column R
Calculate amount of values ​in a column R

Time:03-10

I would like to calculate the amount of 100% and 67% values from my final generated dataset i.e. output1. How can I do this? Every help is welcome.

result<-structure(list(n = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 
28, 29), M1 = c(1L, 29L, 28L, 27L, 25L, 26L, 24L, 20L, 21L, 
22L, 23L, 15L, 12L, 17L, 18L, 19L, 16L, 13L, 14L, 5L, 6L, 7L, 
8L, 9L, 10L, 11L, 4L, 2L, 3L), M2 = c(1, 29, 28, 27, 26, 25, 
24, 23, 22, 21, 20, 15, 12, 19, 18, 17, 16, 14, 13, 11, 10, 9, 
8, 7, 6, 5, 4, 3, 2), M3 = c(1L, 29L, 28L, 27L, 25L, 26L, 24L, 
20L, 21L, 22L, 23L, 15L, 12L, 17L, 18L, 19L, 16L, 13L, 14L, 5L, 
6L, 7L, 8L, 9L, 10L, 11L, 4L, 2L, 3L)), class = "data.frame", row.names = c(NA,-29L))

  ModeFunc <- function(Vec) {
    tmp <- sort(table(Vec),decreasing = TRUE)
    Nms <- names(tmp)
    if(max(tmp) > 1) {
      as.numeric(Nms[1])
    } else NA}

  output1<- result |> rowwise() |> 
    mutate(Mode = ModeFunc(c_across(M1:M3)),
           Percentage = sum(c_across(M1:M3) == Mode) / 3 * 100,
           Percentage = ifelse(is.na(Percentage), "", sprintf("%0.0f%%", Percentage))) %>% 
    data.frame()

  output1<-output1[(-5)] 
  
> output1
    n M1 M2 M3 Percentage
1   1  1  1  1       100%
2   2 29 29 29       100%
3   3 28 28 28       100%
4   4 27 27 27       100%
5   5 25 26 25        67%
6   6 26 25 26        67%
7   7 24 24 24       100%
8   8 20 23 20        67%
9   9 21 22 21        67%
10 10 22 21 22        67%
11 11 23 20 23        67%
12 12 15 15 15       100%
13 13 12 12 12       100%
14 14 17 19 17        67%
15 15 18 18 18       100%
16 16 19 17 19        67%
17 17 16 16 16       100%
18 18 13 14 13        67%
19 19 14 13 14        67%
20 20  5 11  5        67%
21 21  6 10  6        67%
22 22  7  9  7        67%
23 23  8  8  8       100%
24 24  9  7  9        67%
25 25 10  6 10        67%
26 26 11  5 11        67%
27 27  4  4  4       100%
28 28  2  3  2        67%
29 29  3  2  3        67%

CodePudding user response:

We may use count

library(dplyr)
output1 %>% 
 filter(Percentage %in% c("100%", "67%")) %>% 
 count(Percentage)

-output

  Percentage  n
1       100% 11
2        67% 18

tabyl from janitor returns the percentage as well

library(janitor)
output1 %>% 
 filter(Percentage %in% c("100%", "67%")) %>%
 tabyl(Percentage)
 Percentage  n   percent
       100% 11 0.3793103
        67% 18 0.6206897
  •  Tags:  
  • r
  • Related