0

I have a dataset having 216 sound recording files represented by the start and end timing (in seconds) and the respective frequencies of the notes sung by male and female birds:

note sound.files start end freq sex
1 a 2.7 3.2 1.55 f
2 a 3.2 3.6 1.17 m
3 a 3.6 4.0 1.17 f
4 a 3.9 4.3 0.89 m
5 a 4.3 4.4 0.79 f
1 b 1.9 2.3 1.45 f
2 b 2.4 2.7 3.71 m
3 b 2.6 3.1 1.36 f
4 b 3.1 3.4 3.62 m
5 b 3.9 4.4 0.79 m
6 b 4.5 4.6 1.17 f

I require to transform the data in a long format with time-mapped frequency values of male and female birds for each recording, e.g.:

sound.files time m f
a 2.7 0 1.55
a 2.8 0 1.55
a 2.9 0 1.55
a 3.0 0 1.55
a 3.1 0 1.55
a 3.2 1.17 0
a 3.3 1.17 0

I tried the following code but it did not work and running into an error:

Error: Problem with summarise() input ..1. x object 'freq' not found:

code:

cum_call1 <- function(start,end,freq){
  data.frame(time = seq(start,end,by = .1), calling = 1, freq= mean(freq))
}

cum_expand1 <- function(start,end){
  data.frame(time = seq(start,end,by = .1))
}

data.frame$start <- round(data.frame$start,1)
data.frame$end <- round(data.frame$end,1)


duet_call <- data.frame %>% 
  group_by(sound.files,sex,note) %>% 
  summarise(cum_call1(start,end,freq)) %>% 
  ungroup() %>% 
  select(-note)

Is there any right/better way to go about it? Any suggestions are welcome! Thanks in advance!

Roy
  • 21
  • 2

1 Answers1

0

Not base R but the pivot_wider function from one of the tidyverse packages should help. You're pivoting the column to be wider not longer as one column (sex) is becoming two.(m,f)

library(tidyverse)

pivot_wider(data,names_from=sex,values_from=freq)
Nathan
  • 51
  • 6
  • Hi @Nathan, can you please elaborate more? I have a two-step code, where the first step I mentioned in the sample and it was to time-map the data, the second step was to use the transformed file for pivot longer. e.g., `duet_wide <- duet_call %>% pivot_wider(names_from = sex,values_from= freq,id_cols = c(sound.files,time)) %>% unnest(cols = c('f','m')) ` . But I am getting errors in the very first step! – Roy May 31 '22 at 14:11
  • Have you checked that the cum_call function works on its own? The error is happening when summarise calls the returned table from cum_call. – Nathan Jun 01 '22 at 09:36