【发布时间】:2017-11-06 22:56:05
【问题描述】:
我遇到了一个问题,如果满足条件,则将一个值替换为另一个值。我使用自己的函数data_manip,我可以在需要时分配或添加任何其他条件。
但是,当我尝试使用此 data_manip 函数时,它会使用分配的值更改该组中的所有值。但是该特定组中的其他值不符合此条件。
这是我尝试过的,
df <- data.frame(percent = c(0.6, 0.7,1, 0.5,0.5,1,0.4,0.6,1),
type = rep(c("good", "bad","ugly"),each=3), smoke=rep(c('Visky','Wine','Wine'),3),
sex=rep(c('male','male','female'),3))
> df
percent type smoke sex
1 0.6 good Visky male
2 0.7 good Wine male
3 1.0 good Wine female
4 0.5 bad Visky male
5 0.5 bad Wine male
6 1.0 bad Wine female
7 0.4 ugly Visky male
8 0.6 ugly Wine male
9 1.0 ugly Wine female
data_manip <- function(x,gr){
if(grepl('goo|ug',gr)&&x<1){
x[x==0.6] <- 1
}
else
x
}
df%>%
group_by(type)%>%
mutate(percent_new=data_manip(percent,type))
给予
# A tibble: 9 x 5
# Groups: type [3]
percent type smoke sex percent_new
<dbl> <fctr> <fctr> <fctr> <dbl>
1 0.6 good Visky male 1.0
2 0.7 good Wine male 1.0
3 1.0 good Wine female 1.0
4 0.5 bad Visky male 0.5
5 0.5 bad Wine male 0.5
6 1.0 bad Wine female 1.0
7 0.4 ugly Visky male 1.0
8 0.6 ugly Wine male 1.0
9 1.0 ugly Wine female 1.0
如果条件不适合它们,我想保留原始 percent 值。
预期输出
# A tibble: 9 x 5
# Groups: type [3]
percent type smoke sex percent_new
<dbl> <fctr> <fctr> <fctr> <dbl>
1 0.6 good Visky male 1.0
2 0.7 good Wine male 0.7
3 1.0 good Wine female 1.0
4 0.5 bad Visky male 0.5
5 0.5 bad Wine male 0.5
6 1.0 bad Wine female 1.0
7 0.4 ugly Visky male 0.4
8 0.6 ugly Wine male 1.0
9 1.0 ugly Wine female 1.0
【问题讨论】:
-
在
mutate()中尝试ifelse(),ifelse()是一个向量化函数。 -
或在 mutate() 中使用
sapply()任何返回矢量化输出的内容都可以在 mutate 中用于替换或创建新值。 -
@fhlgood 得到与
sapply相同的结果;(
标签: r if-statement dplyr