Gather variables based on condition (R)

∥☆過路亽.° 提交于 2020-02-25 04:05:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!