N. J.
N. J.

Reputation: 105

R - adding values for one column based on a function using another column

I have a dataset that looks like this

head(dataset)

Distance   Lag time  Kurtosis
7.406100   10
144.1700   1
77.31800   1
81.15400   1
4.249167   6

I want to add values to the kurtosis column. To calculate kurtosis I need to group the Distances by Lag time (i.e., all distances for Lag time 1 will give me one value for kurtosis etc.). To get kurtosis I usually use the package "psych" and function describe() Is there a kind of loop I could add to do this?

Upvotes: 1

Views: 125

Answers (2)

Greg
Greg

Reputation: 3670

Since describe produces a dataframe as output and what you want is just one column (also named kurtosis) you'll need to subset the describe output

library(dplyr)
library(psych)

df %>% 
  group_by(Lag_Time) %>% 
  mutate(Kurtosis = describe(Distance)[1,"kurtosis"])

  Distance Lag_Time Kurtosis
     <dbl>    <dbl>    <dbl>
1     7.41       10    NA   
2   144.          1    -2.33
3    77.3         1    -2.33
4    81.2         1    -2.33
5     4.25        6    NA   

Upvotes: 0

Jordan Hackett
Jordan Hackett

Reputation: 749

You should be able to do this using dplyr

library(dplyr)
library(magrittr)
dataset <- dataset %>%
           dplyr::group_by('Lag time') %>%
           dplyr::mutate(Kurtosis = describe(Distance)$kurtosis)

Upvotes: 0

Related Questions