本文介绍了使用dplyr :: mutate()对列的子集上的Row-wise cor()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

set.seed(8)
df <- data.frame(
  A=sample(c(1:3), 10, replace=T), 
  B=sample(c(1:3), 10, replace=T),
  C=sample(c(1:3), 10, replace=T),
  D=sample(c(1:3), 10, replace=T),
  E=sample(c(1:3), 10, replace=T), 
  F=sample(c(1:3), 10, replace=T))

一个dplyr mutate()并进行逐行计算,例如 cor()以获得列AC之间的相关性和DF,但不能弄清楚如何。发现了灵感,这里和,但无法生成可接受的代码。例如,我尝试这样:

Would like to pass a subset of columns into a dplyr mutate() and make a row-wise calculation, for instance cor() to get correlation between column A-C and D-F, but cannot figure out how. Found SO inspiration here, here and here, but nevertheless failed to produce an acceptable code. For instance, I tried this:

require(plyr)
require(dplyr)
df %>%
  rowwise() %>%
  mutate(c=cor(.[[1:3]],.[[4:6]]))


推荐答案

您可以尝试

df %>% 
   rowwise() %>% 
   do(data.frame(., Cor=cor(unlist(.[1:3]), unlist(.[4:6]))))

这篇关于使用dplyr :: mutate()对列的子集上的Row-wise cor()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:48