簡體   English   中英

過濾器/子集R基於其他數據幀的日期幀

[英]Filter/Subset R dateframe based on other dataframe

我有兩個數據幀,一個帶有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
}
}
}

我們可以使用mapply使用一個去申請的條件都replace 我們用NA replace滿足其中一個條件的值。

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

我們也可以做到

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM