1

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?

N. J.
  • 105
  • 6
  • The output of `psych::describe` is a dataframe, not a single variable. It contains a column called "kurtosis" - is that what you want, or you want the whole dataframe? – Greg Mar 10 '20 at 15:58
  • @Greg that's true, I just need the kurtosis column. – N. J. Mar 10 '20 at 16:01

2 Answers2

0

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)
Jordan Hackett
  • 689
  • 3
  • 11
0

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   
Greg
  • 3,570
  • 5
  • 18
  • 31
  • Thank you for your help. It worked. But now I have a follow up question: what can I do to include the lag time "up until" a specific day. For example, for group lag = 5, I want the distance values from 1 till 5 and so on – N. J. Mar 11 '20 at 16:34
  • Likely you can use `filter`, but you should create a new question, including a reproducible example (it's not clear here what you mean by days, since there's no days column) – Greg Mar 11 '20 at 16:41