r - looking for mutate_if, but for rows not columns
问题描述
I am looking for a way to mutate
only certain rows of a dataframe based on two conditions. The first condition is always the same (x==1
). The second is a recode()
of specific values where the first condition is always met.
Here's a very simple version of what I have:
dat <- data.frame(x = c(1, 1, 2, 2),
y = c("a", "b", "a", "b"))
dat
# x y
#1 1 a
#2 1 b
#3 2 a
#4 2 b
Here's what I want:
# x y z
#1 1 a Apple
#2 1 b Banana
#3 2 a a
#4 2 b b
Nested ifelse statements work, but I have a lot of different y
's to define, and I don't want to keep defining x
.
dat %>%
mutate(z = ifelse(x==1 & y=="a", "Apple",
ifelse(x==1 & y=="b", "Banana",
y)))
The following if()
in the pipe does not work, but it's the type of idea I'm going for: when a certain condition is met, do some recoding. I have a lot of recoding to do in my actual use case, so looking for something efficient. I'm trying to do this in the middle of a long pipe that is not shown.
# DOES NOT WORK
dat %>%
{if(x==1)
mutate(.,
z = recode(y,
"a" = "Apple",
"b" = "Banana")
) else
mutate(., z = y)
}
解决方案
推荐阅读
- git - 如何将 git 用于数据科学/机器学习项目
- javascript - 是否可以使用递归函数将 js 对象解析为有效的 html 标记
- vue.js - v-on:click 无论我做什么调整都不能在 vue.js 上工作,我该如何解决这个问题?
- spring-boot - 发布完成中的错误:jgitflow-maven-plugin
- django - 尝试使用表单更新电子邮件时出现“具有此电子邮件地址的自定义用户已存在”错误。姜戈
- imagesharp - 如何在 ImageSharp 中按颜色进行选择?
- c - 如何在 C 中的 Makefile 中编写条件语句?
- autohotkey - (自动热键)COMObject 确实工作,之前它很好。重新安装到新的操作系统 Windows 后,现在它不能做 COM 的事情
- php - Wordpress 在不使用插件的情况下发布多位作者
- python - Why cant i change the error_message of a form in Django?