【问题标题】:Detecting the closest value to a whole number in a set of data in R在R中的一组数据中检测最接近整数的值
【发布时间】:2017-03-07 23:10:35
【问题描述】:

我有一个使用 .wav 文件的 fund() 方法生成的矩阵。整个音频文件为 237 秒,但矩阵包含 20468 行。我想在音频的每一秒都有基频,但数据没有每一秒的干净值。例如:

[86,]   0.98690834 0.2450000  
[87,]   0.99851903 0.1807377  
[88,]   1.01012972 0.2808917  
[89,]   1.02174040 0.2463687  
[90,]   1.03335109 0.2505682  

在这个数据中,第 87 个元素最接近第二个 1 的值,但它不是确切的值。我需要在每一秒内获取最接近的值。我试过这个:

timeSection <- 1:(length(fundData)/2)
for(blah in timeSection){
 fundData[blah,1] <- round_any(fundData[blah,1], 0.001, f= floor)
}

它适用于某些数字,但不适用于所有数字,包括第一秒。

[86,]   0.986 0.2450000  
[87,]   0.998 0.1807377  
[88,]   1.010 0.2808917  
[89,]   1.021 0.2463687  

提前致谢

编辑:我使用@thelatemail 提供的链接之一找到了我需要的东西。

tempValue <- which(abs(fundData[,1]-songDuration) == min(abs(fundData[,1]-songDuration)))

【问题讨论】:

标签: r timestamp


【解决方案1】:

由于我无权访问您的数据,因此我无法告诉您这肯定有效,但我之前曾在类似情况下使用过与此类似的功能。

timeSection <- 1:(length(fundData)/2)
my_fun <- function(x, y){
  which(min(abs(x-y)))
}

rows <- sapply(x = timeSection, my_fun, y = fundData)
df1 <- cbind(timeSection, fundData[rows,])

附带说明,您需要在sapply() 函数的y 参数中指定列

【讨论】:

    【解决方案2】:
    #DATA
    set.seed(42)
    df = data.frame(Time = cumsum(1:500/111), Value = abs(rnorm(500)))    
    
    #Find out indices in df$Time of values closest to 1 through 5
    sapply(1:5, function(a) which.min(abs(a-df$Time)))
    #14 21 25 29 33
    

    【讨论】:

      【解决方案3】:

      data.table 的解决方案

      library(data.table)
      
      #Create a sample dataset
      sample <- data.table(Time = cumsum(1:500/1000), Value = abs(rnorm(500)))
      
      #Order it (not neccessary... was trying a rolling join at first)
      setkey(sample, Time)
      
      #Take the nearest second and also the difference in time between exact time and nearest second
      sample[, ':=' (difference = abs(Time - round(Time)), Nearest_Second = round(Time))]
      
      #take the minimum time difference grouped by each whole second
      sample[, ':=' (mindiff = min(difference), Value = Value) , by = .(Nearest_Second)]
      
      #Only select rows where the difference == minimum difference in time
      sample[difference == mindiff, .(Nearest_Second, Time, Value)]
      

      【讨论】:

        猜你喜欢
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2012-09-18
        • 1970-01-01
        相关资源
        最近更新 更多