Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

r - Select rows from Data.table programmatically based on column criteria

I have a question on the way to select programmatically the rows from a data.table based on values from columns.

Let say I have below Data.table

library(data.table)
DT <- data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)

Now I want to select rows where y = 3 and v = 2

Normally I can use below code

> DT[y==3& v==2]
   x y v
1: a 3 2

But in my case, such selection criteria is itself a variable, and put in a different DF

> DF = data.frame('1' = c('y', 'v'), '2' = c(3,2)); DF
  X1 X2
1  y  3
2  v  2

In this case, the value of X2 above will change, even number of rows is also variable (i.e. assuming I have a bigger DT with more columns, some additional rows in DF might come based on the generation criteria of DF)

Is there any way to use DF to select rows in DT programmatically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option using join:

DT[structure(as.list(DF$X2), names=DF$X1), on=as.character(DF$X1)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...