【问题标题】:Using dplyr to return rows where first character in two columns match and the two rows DO NOT match使用 dplyr 返回两列中的第一个字符匹配且两行不匹配的行
【发布时间】:2016-08-17 17:43:03
【问题描述】:

我有以下数据框:

df <- structure(list(traffic_Count_Street = c("16th St", "17th St", 
                                        "Agnes St", "Ayers St", "Ayers St", "Ayers St", "Ayers St", "Baldwin Blvd", 
                                        "Baldwin Blvd", "Baldwin Blvd","S Brahma Blvd"), 
                     unit_Street = c("Baldwin Blvd", "Baldwin Blvd", "Baldwin Blvd", "Baldwin Blvd", "Baldwin Blvd", 
                      "Baldwin Blvd", "Baldwin Blvd", "Baldwin Blvd", "Baldwin Blvd", 
                     "Baldwin Blvd","S 14th St")), .Names = c("traffic_Count_Street", "unit_Street"
                      ), row.names = c(NA, 11L), class = "data.frame")

   traffic_Count_Street  unit_Street
1               16th St Baldwin Blvd
2               17th St Baldwin Blvd
3              Agnes St Baldwin Blvd
4              Ayers St Baldwin Blvd
5              Ayers St Baldwin Blvd
6              Ayers St Baldwin Blvd
7              Ayers St Baldwin Blvd
8          Baldwin Blvd Baldwin Blvd
9          Baldwin Blvd Baldwin Blvd
10         Baldwin Blvd Baldwin Blvd
11        S Brahma Blvd    S 14th St

我想返回两列不匹配每一行或只有每列的第一个字符匹配的行

结果如下:

  traffic_Count_Street unit_Street
1        S Brahma Blvd   S 14th St

我有以下,但我不确定它是否正确。

require(dplyr)
result = df%>% 
  filter(traffic_Count_Street != unit_Street & traffic_Count_Street[1] == unit_Street[1])

【问题讨论】:

  • 对于此处给出的示例输入,您可能需要显示您期望的输出。此外,在您最近的编辑之后,示例输入给出了“损坏的数据框”警告,因此您可能有一个错误。

标签: r dplyr data-manipulation


【解决方案1】:

我们可以使用substr 提取每列的第一个字符,比较 (==) 和 filter 行以及 OP 代码中的其他比较。

df %>% 
    filter(substr(traffic_Count_Street, 1, 1) == substr(unit_Street, 1, 1) & 
            traffic_Count_Street != unit_Street)
#  traffic_Count_Street unit_Street
#1        S Brahma Blvd   S 14th St

或使用data.table

setDT(df)[df[,Reduce(`!=`, .SD) & substr(.SD[[1]],1,1) == substr(.SD[[2]], 1, 1)]]
#   traffic_Count_Street unit_Street
#1:        S Brahma Blvd   S 14th St

或使用base R

subset(df, substr(traffic_Count_Street, 1, 1) == substr(unit_Street, 1, 1) &              
            traffic_Count_Street != unit_Street)

【讨论】:

  • 最终的答案是 df %>% filter(substr(traffic_Count_Street, 1, 1) == substr(unit_Street, 1, 1)&traffic_Count_Street != unit_Street) ?
  • @DataTx 我也对你的标题、描述和代码感到困惑。如果我使用该代码,则示例中的所有行都不匹配。
【解决方案2】:

使用data.table 获取其糖语法:

library(data.table)
setDT(dat)[substr(traffic_Count_Street, 1, 1) == substr(unit_Street, 1, 1) & 
      traffic_Count_Street != unit_Street]

#    traffic_Count_Street unit_Street
# 1:        S Brahma Blvd   S 14th St

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2017-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多