【发布时间】: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