简体   繁体   English

将具有两个输入的功能应用于数据帧中的数据组

[英]Applying function with two inputs to groups of data in dataframe

I have created a function (pearson) that calls on two vectors (vlow and vhigh) and would like to apply that function to groups of data (dist) in my dataframe (ldf). 我创建了一个函数(Pearson),该函数调用两个向量(vlow和vhigh),并希望将该函数应用于我的数据帧(ldf)中的数据组(dist)。 I have tried to use the following code: 我尝试使用以下代码:

ldf %>% group_by(dist) %>% summarize(pearson(vlow,vhigh))

This is the output: 这是输出:

pearson(vlow, vhigh)
    1            0.5686079

With 5 groups I should be getting 5 results, but for whatever reason its not identifying the groups correctly. 对于5个组,我应该得到5个结果,但是由于某种原因,它不能正确识别组。 Here is what the structure of the dataframe looks like. 数据框的结构如下所示。 Any suggestions as to how I could fix this? 关于如何解决此问题的任何建议?

'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" ...

Best, Thomas 最好,托马斯

Found the answer to my own question. 找到了我自己问题的答案。 If anybody is curious this is the code to make it work: 如果有人好奇,可以使用以下代码进行工作:

# 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM