在列子集上使用dplyr,同时保留其余数据 [英] dplyr on subset of columns while keeping the rest of the data.frame

查看:89
本文介绍了在列子集上使用dplyr,同时保留其余数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用dplyr将函数应用于列的子集。但是,与下面的代码相反,我试图在将所有列都保留在数据框中的同时实现这一点。当前,结果数据框仅保留选定的列。我可以使用remove-cbind构造将这些列合并回原始数据帧,但是我想知道是否有办法直接在dplyr中执行此操作?我曾尝试将SELECT函数移到mutate函数中,但还无法完成这项工作。

I am trying to use dplyr to apply a function to a subset of columns. However, in contrast to the code per below, I am trying to implement this while keeping all columns in the data-frame. Currently, the resulting data-frame only keeps the selected columns. I can use a remove-and-cbind construction to merge these columns back into the original dataframe, but I was wondering if there is a way to do this directly in dplyr? I have tried to move the select function inside the mutate function, but was not able to make this work yet.

require(dplyr)
Replace15=function(x){ifelse(x<1.5,1,x)}
dg <- iris %>%
  dplyr::select(starts_with("Petal")) %>%
  mutate_each(funs(Replace15))  
dg

> dg
Source: local data frame [150 x 2]

   Petal.Length Petal.Width
1           1.0           1
2           1.0           1
3           1.0           1
4           1.5           1
5           1.0           1
6           1.7           1
7           1.0           1
8           1.5           1
9           1.0           1
10          1.5           1


推荐答案

dg <- iris %>% mutate_each(funs(Replace15), matches("^Petal"))

或者(如@aosmith所述),您可以使用 starts_with 。看看?select ,了解 select summarise_each 中其他可用的特殊功能。 code>和 mutate_each。

Alternatively (as posted by @aosmith) you could use starts_with. Have a look at ?select for the other special functions available within select, summarise_each and mutate_each.

这篇关于在列子集上使用dplyr,同时保留其余数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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