根据R中的其他变量创建新变量
与R一起工作,我正在尝试根据数据框架中的3个现有变量创建一个变量。示例:
n <- 20
dat <- data.frame(id=1:n,
group=rep(LETTERS[1:5]),
type=factor(paste("type", 1:2)))
新变量“模型”的值应基于这3:
If "type" = 1 then "model"= apple
If "type" = 2 and "group" A or B, then "model"=cherry
If "type" = 2 and "group" C and "id" 1-4, then"model"= strawberry
If "type" = 2 and "group" C and "id" 5-8, then"model"= melon
If "type" = 2 and "group" C and "id" >9, then "model"=pineapple
我尝试了ifelse
,但我在条件上挣扎。
如何解决这个问题?
Working with R, I am trying to create a variable, based on 3 existing variables in a data frame. Example:
n <- 20
dat <- data.frame(id=1:n,
group=rep(LETTERS[1:5]),
type=factor(paste("type", 1:2)))
The values of the new variable "model" should be based on those 3:
If "type" = 1 then "model"= apple
If "type" = 2 and "group" A or B, then "model"=cherry
If "type" = 2 and "group" C and "id" 1-4, then"model"= strawberry
If "type" = 2 and "group" C and "id" 5-8, then"model"= melon
If "type" = 2 and "group" C and "id" >9, then "model"=pineapple
I have tried with ifelse
, but I struggle with the conditions.
How to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从Tidyverse使用
case_when
:You can use
case_when
from the tidyverse:嵌套
ifelse
选项:输出:
Nested
ifelse
option:Output: