![](/img/trans.png)
[英]How to flag the most efficient way a column of a dataframe by values of another dataframe's in python/pandas?
[英]Most efficient way to replace lowest list values in dataframe in R
我有一個數據框df,其中為每個主題記錄了兩次重復的測試項目,記錄了編號的列表/向量。
subj item rep vec
s1 1 1 [2,1,4,5,8,4,7]
s1 1 2 [1,1,3,4,7,5,3]
s1 2 1 [6,5,4,1,2,5,5]
s1 2 2 [4,4,4,0,1,4,3]
s2 1 1 [4,6,8,7,7,5,8]
s2 1 2 [2,5,4,5,8,1,4]
s2 2 1 [9,3,2,6,6,8,5]
s2 2 2 [7,1,2,3,2,7,3]
對於每個項目,我想找到rep 1的平均值的50%,然后將rep 2向量中的最低數字替換為0,直到rep2的平均值小於或等於rep1的平均值。 例如,對於s1 item1:
mean(c(2,1,4,5,8,4,7))*0.5 = 2.1 #rep1 scaled down
mean(c(1,1,3,4,7,5,3)) = 3.4 #rep2
mean(c(0,0,0,0,7,5,0)) = 1.7 #new rep2 such that mean(rep2) <= mean(rep1)
在除去rep 2向量中的最低編號之后,我想使rep1和rep2向量相關聯,並執行一些其他次要算術函數,並將結果附加到另一個(長度初始化)數據幀中。 現在,我正在使用類似於此偽代碼的循環進行此操作:
for subj in subjs:
for item in items:
while mean(rep2) > mean(rep1)*0.5:
rep2 = replace(lowest(rep2),0)
newDataFrame[i] = correl(rep1,rep2)
用循環執行此操作似乎效率很低。 在R中,是否存在一種更有效的方法來查找和替換列表/向量中的最小值,直到均值小於或等於依賴於該特定項目的值為止? 將關聯和其他結果附加到其他數據幀的最佳方法是什么?
附加信息:
>dput(df)
>structure(list(subj = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L), .Label = c("s1", "s2"), class = "factor"), item = c(1L,
1L, 2L, 2L, 1L, 1L, 2L, 2L), rep = c(1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L), vec = list(c(2, 1, 4, 5, 8, 4, 7), c(1, 1, 3, 4, 7,
5, 3), c(6, 5, 4, 1, 2, 5, 5), c(4, 4, 4, 0, 1, 4, 3), c(4, 6,
8, 7, 7, 5, 8), c(2, 5, 4, 5, 8, 1, 4), c(9, 3, 2, 6, 6, 8, 5
), c(7, 1, 2, 3, 2, 7, 3))), .Names = c("subj", "item", "rep",
"vec"), row.names = c(NA, -8L), class = "data.frame")
我希望此數據幀作為輸出(具有rep1與rep2相關性以及rep1與新rep2相關性)。
subj item origCorrel newCorrel
s1 1 .80 .51
s1 2 .93 .34
s2 1 .56 .40
s2 2 .86 .79
擺脫循環的一種典型策略是將子數據上的所有計算都轉換為自己的函數,然后以aggregate
或apply
函數的形式調用該函數。
two.cors=function(x,ratio=.5) {
rep1=unlist(x[1,][['vec']])
rep2=unlist(x[2,][['vec']])
orig.cor=cor(rep1,rep2)
while(mean(rep2) > mean(rep1)*ratio) {
rep2[ which(rep2==min(rep2[which(!rep2==0)]))]=0
}
c(orig.cor,wierd.cor=cor(rep1,rep2))
}
我想使用daply,所以請獲取plyr
,可以使用聚合或基本*apply
函數
library(plyr)
然后在您的數據集上調用該函數
daply(df,c("subj","item"), .fun=function(x) two.cors(x,ratio=.4) )
可以重新格式化此輸出,但我將其留給了您,因為我認為您需要two.cors
函數之外的其他統計信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.