【问题标题】:How extract values of a data.table based on multiple conditions?如何根据多个条件提取 data.table 的值?
【发布时间】:2019-10-14 17:55:55
【问题描述】:

如何根据多个条件提取data.table的值?

我需要一个函数,它根据其他两个列值返回列 data.table 的值:

require(data.table)

dt <- data.table(
    "base" = c("of", "of", "of", "lead and background vocals", "save thou me from", "silent in the face"),
    "prediction" = c("the", "set", "course", "from", "the", "of"),
    "count" = c(258586, 246646, 137533, 4, 4, 4)
)

> dt
#                         base prediction  count
#1:                         of        the 258586
#2:                         of        set 246646
#3:                         of     course 137533
#4: lead and background vocals       from      4
#5:          save thou me from        the      4
#6:         silent in the face         of      4

# the function needs to return the "prediction" value based on the max "count" value for the input "base" value.
# giving the input "of" to function:
> prediction("of")
# the desired output is:
> "the"
# or:
> prediction("save thou me from")
> "the"

【问题讨论】:

    标签: r function data.table


    【解决方案1】:

    我们可以指定i,根据'count'中的max值提取'prediction'值

    dt[base == 'of', prediction[which.max(count)]]
    #[1] "the"
    dt[base == 'save thou me from', prediction[which.max(count)]]
    #[1] "the"
    

    可以封装成函数

    f1 <- function(val) dt[base == val, prediction[which.max(count)]]
    f1("of")
    #[1] "the"
    f1("save thou me from")
    #[1] "the"
    

    注意:最好将数据集标识符和列名也作为参数

    【讨论】:

    • 该解决方案适用于小型数据集。如何在非常大的 data.table (57M obs) 中快速搜索?
    • @DaniloCorrea 尝试设置密钥setkey(dt, "base"); dt[.('of'), prediction[which(count == max(count))[1]]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2018-01-20
    • 2020-08-11
    • 2023-02-25
    • 2019-07-24
    • 1970-01-01
    相关资源
    最近更新 更多