简体   繁体   中英

data.table SD which.max with a column name

Probably very simple.

I'm trying to use R data.table 's .SD to retain the row with the maximum value by a certain column.

This is my data.frame :

set.seed(1)
dt <- data.frame(id=LETTERS[sample(26,100,replace=T)],value=rnorm(100),stringsAsFactors=F)

And this would be the data.table code:

require(data.table)
dt <- setDT(df)[, .SD[which.max(value)],by=id]

Which works fine.

Now suppose I don't know what the name of the value column is but rather am passed it as a parameter: value.name <- "value"

So I thought this'd work:

dt <- setDT(df)[, .SD[which.max(value.name)],by=id]

But it's throwing the warnings:

 In which.max(value.name) : NAs introduced by coercion

and returning an empty data.table .

Any idea?

您可以使用get()

dt <- setDT(df)[, .SD[which.max(get(value.name))], by = id]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM