Entering a graph into one variable based on another

I have the following structured table (as an example):

   Class 1    Class 2
1   1           1
2   1           1
3   1           1
4   1           2
5   3           3
6   3           3
7   3           4
8   4           4

      

I want to count how many times in a given class 1 the same value appears in class 2 and display that as a percentage. Also the class of group 1. So I want the result to be something like this:

 Class 1     n_class1    Percentage of occurrence in class 2 
1   1           4                  0.75
2   3           3                  0.666
3   4           1                  1.0

      

I read a lot about the dplyr package and think there might be a solution out there and also looked at a lot of examples but no solution has been found yet. I'm new to programming so I don't have a natural programmer, hopefully someone can give me some advice on how to do this.

I was able to get n_class1

using the group but am struggling to get the spawn percentage in class 2.

+3


source to share


2 answers


you can do this by creating a new column in.class1

with mutate

:

library(dplyr)
df <- data.frame(
    class1 = rep(c(1, 3, 4), c(4, 3, 1)),
    class2 = rep(c(1, 2, 3, 4), c(3, 1, 2, 2))
)

df %>%
    mutate(in.class1 = class2 == class1) %>%
    group_by(class1) %>%
    summarise(n_class1 = n(),
              class2_percentile = sum(in.class1) / n()
    )

# # A tibble: 3 × 3
#   class1 n_class1 class2_percentile
#    <dbl>    <int>             <dbl>
# 1      1        4         0.7500000
# 2      3        3         0.6666667
# 3      4        1         1.0000000

      



As suggested by Jaap in a comment, this can be simplified:

df %>%
    group_by(class1) %>%
    summarise(
        n_class1 = n(),
        class2_percentile = sum(class1 == class2) / n())

      

+3


source


The question has already been asked as part of a larger question that the OP asked prior to where he got the answer using data.table

.

Reading data

library(data.table)
cl <- fread(
  "id   Class1    Class2
  1   1           1
  2   1           1
  3   1           1
  4   1           2
  5   3           3
  6   3           3
  7   3           4
  8   4           4"
)

      



Aggregate

cl[, .(.N, share_of_occurence_in_Class2 = sum(Class1 == Class2)/.N), by = Class1]
#   Class1 N share_of_occurence_in_Class2
#1:      1 4                    0.7500000
#2:      3 3                    0.6666667
#3:      4 1                    1.0000000

      

+1


source







All Articles