【问题标题】:R Data Table Return Row Numbers of MatchesR 数据表返回匹配的行数
【发布时间】:2018-04-24 00:03:04
【问题描述】:

我正在使用 data.table 包处理来自 Kaggle 的房价数据集。

当我从数据表语法中检索匹配项时,行号不会与数据一起返回。

combined_df[is.na(GarageArea), garage_num_vars, with = FALSE]

   GarageYrBlt GarageCars GarageArea
1:        1923         NA         NA

如何通过该观察获得实际的行号?我已经看到许多使用 .I 和使用 which = TRUE 的解决方案,但是如何将 which = TRUE 参数添加到我当前的语法中?

【问题讨论】:

  • 为什么不将行号作为列添加到原始数据中?
  • 换句话说,将数据转换为 data.table 时,请指定 keep.rownames 参数,如 setDT(df, keep.rownames = TRUE)

标签: r data.table


【解决方案1】:

除了按照注释中的建议添加一列行号之外,还可以这样使用which参数:

DT <- data.table(val = c(1, 2, 3, NA, 4))
# > DT
#    val
# 1:   1
# 2:   2
# 3:   3
# 4:  NA
# 5:   4

x <- DT[is.na(val), which = TRUE]

cbind(rownum = x, DT[x])
#    rownum val
# 1:      4  NA

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2016-03-17
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多