0
Follow
0
View

how to create a frequency variable of occurence of a value per name per year in R (dataframe)

diyuershi 注册会员
2023-01-25 03:32

Here is another dplyr solution:

library(dplyr)
df %>% 
  group_by(Name, Year) %>% 
  mutate(Count = ifelse(wi == 1, sum(wi), sum(wi)),
         req_wi = Count/sum(Count)*Count) %>% 
  ungroup() %>% 
  select(-Count)
    Name   Year    id    wi req_wi
        
 1 x      2011     8     1  0.667
 2 x      2011    23     0  0.667
 3 x      2011     1     1  0.667
 4 x      2012     5     1  0.5  
 5 x      2012     7     0  0.5  
 6 y      2011    25     1  1    
 7 y      2011    83     1  1    
 8 y      2012     6     0  0.25 
 9 y      2012     2     0  0.25 
10 y      2012     9     1  0.25 
11 y      2012    10     0  0.25 
gsdhdsz 注册会员
2023-01-25 03:32

If wi is always 0 or 1 you can do the following (because mean(wi) is then equal to "frequency of wi")

library(dplyr)
    df %>% 
      group_by(Name, Year) %>% 
      summarise(freq_wi=mean(wi)) %>% 
      left_join(df, .)

       Name   Year    id    wi freq_wi
             
     1 x      2011     8     1   0.667
     2 x      2011    23     0   0.667
     3 x      2011     1     1   0.667
     4 x      2012     5     1   0.5  
     5 x      2012     7     0   0.5  
     6 y      2011    25     1   1    
     7 y      2011    83     1   1    
     8 y      2012     6     0   0.25 
     9 y      2012     2     0   0.25 
    10 y      2012     9     1   0.25 
    11 y      2012    10     0   0.25 

About the Author

Question Info

Publish Time
2023-01-25 03:32
Update Time
2023-01-25 03:32

Related Question