当使用 R 满足某些条件时,使用两列创建一个新变量
我提供此示例数据是为了表达我的问题。
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 的新变量(列),并满足以下条件:
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 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)
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
I tried to use the "ifelse" function but fell short.
I hope that the question is clear enough.
Thanks for all the help,
Bazon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ramnath 的解决方案非常出色,但是要使用
ifelse
来实现,您可以这样做:但这意味着
foson
或fosof
中的任何一个code> 是<1
,它将选择==0
的选项,但从您的数据来看,这似乎不是问题。The solution by Ramnath is excellent, but to do it with
ifelse
you could do it this way:This would however mean that where any of
foson
orfosof
are<1
it would select the option for==0
, but it seems from your data this would not be an issue.一种可能的解决方案是执行以下操作
这应该会给您带来所需的结果。
One potential solution is to do the following
This should give you the desired result.