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))
想要将列的子集传递到 dplyrmutate()
并进行逐行计算,例如cor()
获得 A-C 列和 D-F 列之间的相关性,但不知道如何实现。找到了灵感here https://stackoverflow.com/questions/28159143/add-column-with-row-wise-mean-over-selected-columns-using-dplyr, here https://stackoverflow.com/questions/21818181/applying-a-function-to-every-row-of-a-table-using-dplyr and here https://stackoverflow.com/questions/28751023/performing-dplyr-mutate-on-subset-of-columns,但仍然未能产生可接受的代码。例如,我尝试过这个:
require(plyr)
require(dplyr)
df %>%
rowwise() %>%
mutate(c=cor(.[[1:3]],.[[4:6]]))