当两列满足特定条件时,使用R创建一个新变量 [英] creating a new variable using two columns when they satisfy certain conditions using R

查看:575
本文介绍了当两列满足特定条件时,使用R创建一个新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在提供此示例数据来阐明我的问题.

I am providing this example data to get my question across.

aid=c(1,2,3,4,5,6,7,8,9,10)
foson=c(0,1,2,0,6,9,0,0,3,0)
fosof=c(0,0,2,3,0,0,0,5,0,0)
data=data.frame(aid,foson,fosof)

现在,我需要在以下条件下创建一个名为data $ hist的新变量(列):

Now, I need to create a new variable (column) named data$hist with the following conditions:

if foson==0 and fosof==0, then hist = 0;
if foson >=1 and fosof==0, then hist = 1;
if foson==0 and fosof>=1, then hist = 2; and
if foson>=1 and fosof>=1, then hist = 3

我尝试使用"ifelse"功能,但失败了.

I tried to use the "ifelse" function but fell short.

我希望这个问题足够清楚.

I hope that the question is clear enough.

感谢所有帮助

Bazon

推荐答案

Ramnath的解决方案非常出色,但是要使用ifelse做到这一点,您可以这样做:

The solution by Ramnath is excellent, but to do it with ifelse you could do it this way:

data$hist <- ifelse(data$foson>=1,ifelse(data$fosof>=1,3,1),ifelse(data$fosof>=1,2,0))

但是,这意味着fosonfosof中的任何一个为<1时,它将选择==0的选项,但是从您的数据看来,这将不是问题.

This would however mean that where any of foson or fosof are <1 it would select the option for ==0, but it seems from your data this would not be an issue.

这篇关于当两列满足特定条件时,使用R创建一个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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