Filter data table by dynamic column name

前端 未结 4 1496
失恋的感觉
失恋的感觉 2020-12-11 06:40

lets say I have a data.table with columns A, B and C

I\'d like to write a function that applies a filter (for example A>1) but \"A\" needs to be dynamic (the functio

4条回答
  •  粉色の甜心
    2020-12-11 07:22

    If your data is

    a <- c(1:9)
    b <- c(10:18)
    # create a data.frame
    df <- data.frame(a,b)
    # or a data.table
    dt <- data.table(a,b)
    

    you can store your condition(s) in a variable x

    x <- quote(a >= 3)
    

    and filter the data.frame using dplyr (subsetting with [] won't work)

    library(dplyr)
    filter(df, x)
    

    or using data.table as suggested by @Frank

    library(data.table)
    dt[eval(x),]
    

提交回复
热议问题