问题
I'm working through the book "R for Data Science" and would like to "gather" several variables from the dataset based on a condition (similar to select). Specifically, I want to pick just the continuous variables not the categorical ones.
How can I accomplish this without manually specifying the variables? Below does not work...
library(tidyverse)
diamonds %>%
gather(key, value, is.numeric(key))
回答1:
I'm sure there are better ways to do this but gather()
can take column positions as the selection argument so you can use:
diamonds %>%
head(10) %>%
gather(key, value, which(sapply(., is.numeric)))
来源:https://stackoverflow.com/questions/52529822/gather-variables-based-on-condition-r