【问题标题】:select first nth percent of rows from random sampled dataframes of list in r从 r 中列表的随机采样数据帧中选择前 n% 的行
【发布时间】:2017-08-27 18:54:20
【问题描述】:

我编写了一个函数,它从数据框中选择前 n% 的行(即阈值),这也适用于列表的数据框。功能如下:

set.threshold.rand <-function(value, vector){
  print(length(vector))
  n<-as.integer(length(vector)/100*value)
  threshold<-vector[n]
  return(threshold)
}

sensitivity.rand<-function(vector, threshold){
  thresh<-set.threshold.rand(threshold, vector)
  print(thresh)
  score<-ifelse(vector<=thresh, "H", "L") # after taking the threshold values it assign them to 'H' and 'L' according to condition
  return(score)
}

此函数从列表的数据框中选择前 n% 的行。例如,下面的代码选择前 143 行作为预期的“H”。

vec.1 <- c(1:574)
vec.2 <- c(3001:3574)
df.1 <- data.frame(vec.1, vec.2)
df.2 <- data.frame(vec.2, vec.1)

my_list1 <- list(df.1, df.2)
my_list1 <- lapply(my_list1, function(x) {x[1] <- lapply(x[1], sensitivity.rand, threshold = 25) 
x})

但这不适用于列表的采样和复制数据帧(如下所示)。例如:

my_list <- replicate(10, df.1[sample(nrow(df.1)),] , simplify = FALSE)

my_list <- lapply(my_list, function(x) {x[1] <- lapply(x[1], sensitivity.rand, threshold = 25) 
x})

这些选择超过 300 行。如何解决?

【问题讨论】:

    标签: r list function dataframe lapply


    【解决方案1】:

    改编自#SirSaleh here 给出的答案:

    sensitivity.rand <- function(vector, threshold){
      num_to_thres <- floor(threshold*0.01*length(vector))
      l = length (vector)
      score = c(rep("H",num_to_thres),rep("L",l-num_to_thres))
      return(score)
    }
    

    现在它可以采用任何阈值并且效果很好。

    【讨论】:

      【解决方案2】:

      您的函数set.threshold.rand 依赖于输入向量已排序这一事实。

      这就是它适用于 my_list1 而不是 my_list 的原因,在 sample() 中,您已经对行进行了洗牌。

      set.threshold.rand 中将threshold &lt;- vector[n] 替换为threshold &lt;- sort(vector)[n]

      【讨论】:

      • 如果我在set.threshold.rand 中使用threshold &lt;- sort(vector)[n],它会将my_list 中的值从低到高排序,并将前25% 作为“H”(即1-143 有“H”) .但我想在排序的数据框中将前 25% 作为“H”(前 25% 行中的任何值都将具有“H”)。如何解决?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 2014-07-12
      相关资源
      最近更新 更多