r - 有没有办法在 R 中使用 dplyr 根据另一个列的值创建一个新列?
问题描述
我一直在使用 base R,但我想使用dplyr
. 这就是我一直在做的事情:
data$newvariable <- 0
data$newvariable[data$oldvariable=="happy"] <- "good"
data$newvariable[data$oldvariable=="unhappy"] <- "bad"
data$newvariable[data$oldvariable=="depressed"] <- "super_bad"
解决方案
如果 oldvariable 是一个因素,并且您不介意 newvariable 是一个因素:
library(dplyr)
set.seed(111)
data = data.frame(
oldvariable=sample(c("happy","unhappy","depressed"),10,replace=TRUE))
data %>% mutate(newvariable=recode_factor(oldvariable,
"happy"="good","unhappy"="bad","depressed"="super_bad"))
oldvariable newvariable
1 unhappy bad
2 depressed super_bad
3 depressed super_bad
4 depressed super_bad
5 happy good
6 depressed super_bad
7 happy good
8 depressed super_bad
9 unhappy bad
10 happy good
推荐阅读
- java - 改造响应 500 空消息
- python - 我想制作一个随机数字和字母生成器,但这不起作用
- java - 为什么 Admob 插页式广告不显示在 AndroidOS 上?
- android - Jetpack Compose - 如何从 pointerInteropFilter 中提取目标
- r - 正则表达式字符串匹配单词模式
- ansible - ansible - 当 result.stdout 超过 1 行时失败
- python - 如何使用全局变量更新标签
- websphere - 如何将 IBM Maximo Websphere 主机添加到 Windows Server 网络负载平衡集群?
- bootstrap-4 - 如何仅在索引页面上显示轮播并使其适合整个屏幕?- asp.net 核心 mvc 引导程序
- javascript - 如何在反应中使用类 npm 包