过滤器/子集R基于其他数据帧的日期帧

问题描述 投票:1回答:2

我有两个数据帧,一个带有corr矩阵,另一个带有相应的p值(即两个都是有序的,每个数据帧中的每个位置对应同一个变量)。我想基于2个条件过滤corr数据帧中的元素:

1)将每列与该列第一行中的元素进行比较,较小的元素应为NA或0。

2)如果第二个数据帧中的相应元素大于0.05,则该元素应再次变为0。

一个例子看起来像这样:

set.seed(2)
a = sample(runif(5)  ,rep=TRUE) 
b = sample(runif(5)  ,rep=TRUE)
c = sample(runif(5)  ,rep=TRUE)
corr_mat = data.frame(a,b,c)       

a = sample(runif(5,0,0.1)  ,rep=TRUE) 
b = sample(runif(5,0,0.1)  ,rep=TRUE)
c = sample(runif(5,0,0.1)  ,rep=TRUE)
p_values= data.frame(a,b,c)   

所以我想以这样的方式对corr_mat进行子集:在列a中只剩下那些值大于列a中的行1并且p_values中的对应p值小于0.05。

这是我想要为这些值输出的输出:

 > corr_mat
      a         b         c
 1 0.9438393 0.4052822 0.8368892
 2 0.1848823 0.4052822 0.6618988
 3 0.9438393 0.2388948 0.3875495
 4 0.5733263 0.7605133 0.3472722
 5 0.5733263 0.5526741 0.6618988

 > p_values
        a          b          c
 1 0.086886104 0.01632009 0.02754012
 2 0.051428176 0.09440418 0.09297202
 3 0.016464224 0.02970107 0.02754012
 4 0.086886104 0.01150841 0.09297202
 5 0.001041453 0.09440418 0.09297202

目标输出(基于第一个条件,大于或等于每列的第一行值):

 > corr_mat
      a         b         c
 1 0.9438393 0.4052822 0.8368892
 2           0.4052822  
 3 0.9438393            
 4           0.7605133  
 5           0.5526741  

目标输出(基于两个条件 - 现在排除相应的p值大于0.05):

 > corr_mat
      a         b         c
 1 0.9438393 0.4052822 0.8368892
 2             
 3 0.9438393            
 4           0.7605133  
 5             

我正在思考以下问题:

 apply(corr_mat_df,2, comp)

其中comp定义为比较corr_mat中列a的第1行和p_values中相应元素的内容。

comp<-function(df1,df2) {
for (i in 1:length(df1)) {
if (df[i]<df[1] & df2[i]>0.05){
  df[i]=NA
}
}
}
r dataframe subset
2个回答
2
投票

我们可以使用mapply使用replace一次性应用这两个条件。我们replace满足NA条件之一的值。

mapply(function(x, y) replace(x, (x < x[1]) | (y > 0.05), NA),corr_mat, p_values)


#             a         b         c
#[1,]        NA 0.4052822 0.8368892
#[2,]        NA        NA        NA
#[3,] 0.9438393        NA        NA
#[4,]        NA 0.7605133        NA
#[5,]        NA        NA        NA

1
投票

我们也可以做到

corr_mat *NA^(corr_mat < corr_mat[1,][col(corr_mat)] | p_values > 0.05 )
#         a         b         c
#1        NA 0.4052822 0.8368892
#2        NA        NA        NA
#3 0.9438393        NA        NA
#4        NA 0.7605133        NA
#5        NA        NA        NA

或者只是分配

corr_mat[corr_mat < corr_mat[1,][col(corr_mat)] | p_values > 0.05] <- NA
© www.soinside.com 2019 - 2024. All rights reserved.