【问题标题】:Comparing Values in Individual Rows to Corresponding Rows In Different Column将单独行中的值与不同列中的对应行进行比较
【发布时间】:2013-08-06 05:00:06
【问题描述】:

我是论坛的新手,对 R 比较陌生。

我目前正在处理我的数据。数据放置在 DataFrame 中。我想将“Prime”列的每一行中的值与“target”列的每一对应行进行比较。如果值匹配,我想将值“1”添加到“匹配”列中的相应行,如果它们不匹配,则添加“0”。

以下是“匹配”列下的列示例和解决方案

Prime    Target  Match
faces0   faces0   1 
faces0   faces0   1 
houses1  faces0   0

我尝试过使用ifelseidentical,但它会将对象作为一个整体进行比较,而不是单独和相应的行。

任何人都可以提出一种比较 Prime 和 Target 的方法,同时根据是否进行匹配来为 Match 分配一个值吗?

非常感谢您的宝贵时间。

【问题讨论】:

    标签: r match rows


    【解决方案1】:

    这是一个直接的逻辑测试,所以如果你比较两列是否相等,你会得到TRUE/FALSE,它可以很容易地转换为1/0as.numeric()。根据列的编码方式,可能需要在比较之前将它们转换为字符:

    dat$Match <- as.numeric(dat$Prime == dat$Target)
    dat$Match
    # [1] 1 1 0
    

    【讨论】:

    • 这是一个漂亮而优雅的解决方案。它奏效了。非常感谢。
    【解决方案2】:

    您可以使用ifelsematch,但在此之前需要转换为数字。这是解决方案。

    mydata<-structure(list(Prime = structure(c(1L, 1L, 2L), .Label = c("faces0", 
    "houses1"), class = "factor"), Target = structure(c(1L, 1L, 1L
    ), .Label = "faces0", class = "factor"), Match = c(1, 1, 0)), .Names = c("Prime", 
    "Target", "Match"), row.names = c(NA, -3L), class = "data.frame")
    
    > mydata$Match<-with(mydata,ifelse(as.numeric(Prime)==as.numeric(Target),1,0))
    > mydata
        Prime Target Match
    1  faces0 faces0     1
    2  faces0 faces0     1
    3 houses1 faces0     0
    
    mydata$Match<-with(mydata,match(as.numeric(Prime),as.numeric(Target),nomatch=0))
     > mydata
            Prime Target Match
        1  faces0 faces0     1
        2  faces0 faces0     1
        3 houses1 faces0     0
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多