[英]Applying function with two inputs to groups of data in dataframe
我創建了一個函數(Pearson),該函數調用兩個向量(vlow和vhigh),並希望將該函數應用於我的數據幀(ldf)中的數據組(dist)。 我嘗試使用以下代碼:
ldf %>% group_by(dist) %>% summarize(pearson(vlow,vhigh))
這是輸出:
pearson(vlow, vhigh)
1 0.5686079
對於5個組,我應該得到5個結果,但是由於某種原因,它不能正確識別組。 數據框的結構如下所示。 關於如何解決此問題的任何建議?
'data.frame': 157 obs. of 5 variables:
$ dlow : num 24 33 45 123 30 33 126 84 87 81 ...
$ dhigh: num 27 36 48 126 33 36 129 87 90 84 ...
$ vlow : num 251 249 251 254 251 ...
$ vhigh: num 248 250 251 254 250 ...
$ dist : chr "3" "3" "3" "3" ...
最好,托馬斯
找到了我自己問題的答案。 如果有人好奇,可以使用以下代碼進行工作:
# Split data by lag
sp <- split(ldf, ldf$dist)
# Calculate Pearson Correlation (p)
p <- lapply(names(sp), function(x) pearson(sp[[x]][["vlow"]],sp[[x]][["vhigh"]]))
p <- unlist(p)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.