I want to calculate the mean of some columns using dplyr::mutate.
library(dplyr)
test <- data.frame(replicate(12, sample(1:12, 12, rep = T))) %>%
`colnames<-`(seq(1:12) %>% paste("BL", ., sep = ""))
The columns I want to include to calculate the mean are ONLY BL1 to BL9, so I do
test_again <- test %>%
rowwise() %>%
mutate(ave = mean(c(seq(1:9) %>% paste("BL", ., sep = ""))))
This would not work. I notice if I put the column one by one, it works
test_againAndAgain <- test %>%
rowwise() %>%
mutate(ave = mean(c(BL1, BL2, BL3, BL4, BL5, BL6, BL7, BL8, BL9)))
I suspected it's because I give the strings instead of "columns".
Can somebody explain this behavior? What will be the best solution for this?