Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to pass a list of columns to data.table where some are predetermined

Pass character vectors and column names to data.table as a list of columns?

I want to be able to produce a subset of columns in R using data.table in a way that I can determine some of them earlier on and pass the predetermined list on as a character vector, then combine with a static list of columns.

That is, given this:

a <- 1:4
b <- 5:8
c <- c('aa','bb','cc','dd')
e <- 1:4

z <- data.table(a,b,c,e)

I want to do this:

z[, list(a,b)]

Which produces this output:

   a b
1: 1 5
2: 2 6
3: 3 7
4: 4 8

But I want to do it in some way similar to this (which works, almost):

cols <- "b"
z[, list(get(cols), a)]

Results: Note that it doesn't return the name of the column stored in cols

   V1 a
1:  5 1
2:  6 2
3:  7 3
4:  8 4

but I need to do it with more than one element of cols (which does not work):

cols <- c('a', 'b')
z[, list(mget(cols), c)]

The above produces the following error:

Error: value for ‘a’ not found

I think my problem lies with scoping and which environments mget is looking in, but I can't figure out what exactly I am doing wrong. Also, how do I preserve the column titles?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here are two (pretty much equivalent) options. One using lapply:

z[, c(lapply(cols, get), list(c))]
#   V1 V2 V3
#1:  1  5 aa
#2:  2  6 bb
#3:  3  7 cc
#4:  4  8 dd

And one using mget:

z[, c(mget(cols, inherits = TRUE), c = list(c))]
#   a b  c
#1: 1 5 aa
#2: 2 6 bb
#3: 3 7 cc
#4: 4 8 dd

Note that get returns a vector which loses the information about column name (and there isn't much you can do about it besides manually adding it back in), while mget returns a named list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...