基于R中的组的数据帧中两列的相关比率

时间:2018-10-12 19:28:25

标签: r dplyr correlation

我正在尝试根据另一列的唯一值找到数据框中两列之间的相关比率(我认为这是正确的术语,不擅长统计)。我不确定我是否使用正确的功能。我希望以下数字以黄色突出显示。我似乎无法获得想要的东西。不胜感激。

enter image description here

样本数据:

test_df<-structure(list(stdate = c("2015-06-25", "2015-06-25", "2015-06-29", 
"2015-06-29", "2008-05-05", "2008-05-05", "2015-06-30", "2015-06-30", 
"2015-06-30", "2017-11-15", "2017-11-15", "2017-11-13", "2017-11-13", 
"2015-08-31", "2015-08-31", "2008-05-01", "2008-05-01", "2017-02-14", 
"2017-02-14", "2017-02-13"), sttime = c("10:30:00", "10:30:00", 
"09:45:00", "09:45:00", "11:50:00", "11:50:00", "10:45:00", "10:45:00", 
"09:00:00", "09:50:00", "09:50:00", "09:10:00", "09:10:00", "13:50:00", 
"13:50:00", "09:30:00", "09:30:00", "10:30:00", "10:30:00", "08:30:00"
), locid = c("USGS-01388500", "USGS-01388500", "USGS-01464585", 
"USGS-01464585", "USGS-01464515", "USGS-01464515", "USGS-01407330", 
"USGS-01407330", "USGS-01466500", "USGS-01387500", "USGS-01387500", 
"USGS-01395000", "USGS-01395000", "USGS-01400860", "USGS-01400860", 
"USGS-01377000", "USGS-01377000", "USGS-01367625", "USGS-01367625", 
"USGS-01398000"), Specific_conductance = c(525, 525, 184, 184, 
226, 226, 203, 203, 41, 674, 674, 466, 466, 312, 312, 540, 540, 
844, 844, 683), tds = c(294, 275, 119, 100, 155, 116, 155, 115, 
43, 403, 382, 286, 274, 177, 173, 328, 277, 435, 440, 347)), .Names = c("stdate", 
"sttime", "locid", "Specific_conductance", "tds"), row.names = c(NA, 
20L), class = "data.frame")

代码:

correlation_df<-test_df%>%
       group_by(locid)%>%
       summarise(correl=cor(tds,Specific_conductance))

运行此命令时,我得到的NA是1乘1的数据帧。我想要每个locid的值

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用完整数据运行该代码?在您的test_df中,每个locid仅具有两个条目,因此它试图将两个数字相关联(这将始终给出NA)。如果我用更多数据组成一个虚拟数据帧,则可以正常工作:

test_df <- tibble(locid = rep(c("a", "b", "c", "d"), 100), tds = rnorm(400), 
Specific_conductance = rnorm(400))

correlation_df <- test_df%>%
  group_by(locid)%>%
  summarise(correl = cor(tds,Specific_conductance))
correlation_df