从r中的列表的随机采样数据帧中选择前n%的行 [英] select first nth percent of rows from random sampled dataframes of list in r
问题描述
我写了一个函数,它从数据框中选择第一个百分之几的行(即阈值),这也适用于列表的数据框。这些函数如下所示:
set.threshold.rand< -function(value,vector){
print (长度(矢量))
n <-as.integer(长度(矢量)/ 100 *值)
阈值<-vector [n]
返回(阈值)
}
sensitivity.rand< -function(vector,threshold){
thresh <-set.threshold.rand(threshold,vector)
print(thresh)
score< ;根据条件
返回(分数)
},在获得阈值后,它将它们分配给'H'和'L',从而得到(矢量<=阈值,H,L
该函数从列表的数据框中选择前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)),] ,简化= FALSE)
my_list< - lapply(my_list,function(x){x [1]< - lapply(x [1],sensitivity.rand,threshold = 25)
$ b))
这些选择的行数超过300。如何解决这个问题?
您的函数 set.threshold.rand
依赖于输入向量被排序的事实。
这就是为什么它可以和 my_list1
并且不与 my_list
,其中你用 sample()
整理了行。
将
阈值< - vector [n]
替换为阈值< - sort(vector)[n]
在 set.threshold.rand
I wrote a function that selects first nth percent of rows (i.e., threshold) from dataframe and this works on dataframes of list as well. The functions is given below:
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)
}
This function selects first nth percent of rows from dataframes of list. For example, the codes below selects first 143 rows as "H" which was expected.
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})
But this don't work on sampled and replicated dataframes of list (given below). For example:
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})
These select more than 300 number of rows. How to solve this?
Your function set.threshold.rand
relies on the fact that the input vector is sorted.
That's why it works with my_list1
and not with my_list
, where you've shuffled the rows with sample()
.
Replace threshold <- vector[n]
with threshold <- sort(vector)[n]
in set.threshold.rand
这篇关于从r中的列表的随机采样数据帧中选择前n%的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!