dplyr 在列的子集上,同时保留 data.frame 的其余部分
dplyr on subset of columns while keeping the rest of the data.frame
我正在尝试使用 dplyr 将函数应用于列的子集。但是,与下面的代码相反,我试图在将所有列保留在数据框中的同时实现这一点。目前,生成的数据框仅保留 selected 列。我可以使用 remove-and-cbind 结构将这些列合并回原始数据帧,但我想知道是否有办法直接在 dplyr 中执行此操作?我试图将 select 函数移动到 mutate 函数中,但还无法完成这项工作。
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
和 mutate_each.
中可用的其他特殊函数
mutate_each
is now deprecated,替换为 mutate_if
和 mutate_at
。使用这些替换,答案是
dg <- iris %>% mutate_at(vars(starts_with("Petal")), funs(Replace15))
我正在尝试使用 dplyr 将函数应用于列的子集。但是,与下面的代码相反,我试图在将所有列保留在数据框中的同时实现这一点。目前,生成的数据框仅保留 selected 列。我可以使用 remove-and-cbind 结构将这些列合并回原始数据帧,但我想知道是否有办法直接在 dplyr 中执行此操作?我试图将 select 函数移动到 mutate 函数中,但还无法完成这项工作。
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
和 mutate_each.
mutate_each
is now deprecated,替换为 mutate_if
和 mutate_at
。使用这些替换,答案是
dg <- iris %>% mutate_at(vars(starts_with("Petal")), funs(Replace15))