当使用 R 满足某些条件时,使用两列创建一个新变量

发布于 2024-09-17 13:45:32 字数 505 浏览 9 评论 0原文

我提供此示例数据是为了表达我的问题。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

欲拥i 2024-09-24 13:47:09

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

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

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

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))

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.

十六岁半 2024-09-24 13:46:47

一种可能的解决方案是执行以下操作

data$hist = (data$foson >=1) + (data$fosof >=1)*2

这应该会给您带来所需的结果。

One potential solution is to do the following

data$hist = (data$foson >=1) + (data$fosof >=1)*2

This should give you the desired result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文