【问题标题】:creating a new variable using two columns when they satisfy certain conditions using R当它们满足使用 R 的某些条件时,使用两列创建一个新变量
【发布时间】:2011-04-07 15:07:37
【问题描述】:

我提供此示例数据来解决我的问题。

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”功能,但未能成功。

我希望问题足够清楚。

感谢大家的帮助,

巴松

【问题讨论】:

    标签: r conditional-statements multiple-columns


    【解决方案1】:

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

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

    这应该会给你想要的结果。

    【讨论】:

    • 嗨,Ramnath,成功了!我只是想完全理解整行(语法).....尤其是行尾的 *2 位。Bazon
    • 它使用逻辑值(TRUE,FALSE)也可以用数字(1,0)的事实。它只是将所有 foson 设置为 1 或 0 并将所有 fosof 设置为 2 (1*2) 或 0 并添加它们。这实际上是一个很棒的解决方案……C 程序员会想到的。
    【解决方案2】:

    Ramnath 的解决方案非常好,但要使用 ifelse,您可以这样做:

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

    然而,这意味着如果fosonfosof 中的任何一个是&lt;1,它将选择==0 的选项,但从您的数据看来这不会是一个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2019-11-18
      • 2020-09-18
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多