Home > OS >  How do I Divide Values in a Column by the Value in the Last Cell?
How do I Divide Values in a Column by the Value in the Last Cell?

Time:02-15

So I am working in R, and I am trying to write a function. But I reached a roadblock.

I have the following df:

Number Freq CumFreq
00.1 2 2
00.5 1 3

...so on and so forth.

I'd like to have it so the numbers in df$CumFreq are divided by the last cell in the df$CumFreq, and create a new column. For instance:

Number Freq CumFreq CF/n
00.1 2 2 0.667
00.5 1 3 1

Any advice on how to write this out?

CodePudding user response:

You can try

df$CFn <- with(df,CumFreq/sum(Freq))

or

df$CFn <- with(df,CumFreq/tail(CumFreq,1))

CodePudding user response:

Here's a dplyr approach using mutate:

df %>% mutate("CF/n" = CumFreq/sum(Freq))

  Number Freq CumFreq      CF/n
1   00.1    2       2 0.6666667
2   00.5    1       3 1.0000000
  • Related