dplyr:基于一个变量中的值按行替换值 [英] dplyr: Replace values rowwise based on value in one variable

查看:48
本文介绍了dplyr:基于一个变量中的值按行替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从分析中排除参与者(年龄> 90岁).通常我会那样做:

I want to exclude participants from an analysis that are too old (age >90). Usually I would do it like that:

df <- data.frame(age=c(1,10, 100), x= 1:3, y= 1:3)
df[df$age > 90, ] <- NA

我不知道如何使用dplyr做到这一点.如果要替换一个变量,可以使用

I can't figure out how to do this with dplyr. If we want to replace one variable we can use

library(dplyr)
df <- data.frame(age=c(1,10, 100), x= 1:3, y= 1:3)
df %>%
  mutate(age= replace(age, age> 90, NA))

所以我认为我可以使用

df %>%
  mutate_all(function(i) replace(i, age> 90, NA))

我也尝试了 mutate_if mutate_at ,但没有成功.在阅读了关于SO的问题之后,我认为问题"是在我的情况下,我需要使用dplyr更改 rowwise 的值.

I also tried mutate_if and mutate_at but it did not work out. After reading questions on SO I think the "problem" is that in my situation I need to change the values rowwise with dplyr.

推荐答案

您需要以一种方式排列列,以使测试列( age )在最后.

You need to arrange the columns in a way such that the test column (age) is the last.

library(dplyr)
df %>%
  select(x, y, age) %>%
  mutate_all(~replace(.x, age> 90, NA))

#   x  y age
#1  1  1   1
#2  2  2  10
#3 NA NA  NA

这篇关于dplyr:基于一个变量中的值按行替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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