0

i have a df structured like this:

 Value.  Numb. 
   46.   200
   47.   200
   55.   200
   21.   200
   32.   140
   23.   140
   56.   700

If numb value is repeated, I want to substitute the value with the result of the division Numb/number of times it appears, obtaining a new df:

 Value.  Numb. 
   46.    50
   47.    50
   55.    50
   21.    50
   32.    70
   23.    70
   56.   700

How can I do? better a solution comprising the use of dplyr.

Silvia
  • 405
  • 4
  • 17

3 Answers3

2
library(dplyr)
df %>% group_by(Numb.) %>% mutate(Number=Numb./n()) %>% ungroup()
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
1

One way using ave is to create a grouping variable Numb and calculate the length of each group and divide the Numb by the length.

with(df, Numb/ave(Numb, Numb, FUN = length))
#[1]  50  50  50  50  70  70 700
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

One option is data.table. Grouped by 'Numb.', divide the column by the number of rows

library(data.table)
setDT(df)[, Numb. := Numb./.N, Numb.]
akrun
  • 874,273
  • 37
  • 540
  • 662