根据条件收集变量 (R) [英] Gather variables based on condition (R)

查看:39
本文介绍了根据条件收集变量 (R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读R for Data Science"一书,并想根据条件(类似于选择)从数据集中收集"几个变量.具体来说,我只想选择连续变量而不是分类变量.

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))

推荐答案

我确信有更好的方法可以做到这一点,但 gather() 可以将列位置作为选择参数,因此您可以使用:

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)))

这篇关于根据条件收集变量 (R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆