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
1.6k views
in Technique[技术] by (71.8m points)

r - Dynamically add column names to data.table when aggregating

I know we can dynamically add column names when creating columns by reference (using :=), as described e.g. here: Dynamic column names in data.table.

However, I'm looking to dynamically add column names when we aggregate. Can you help with this?

test_dtb <- data.table(a = sample(1:100, 100), b = sample(1:100, 100), id = rep(1:10, 10))
m = "blah"
test_dtb[ , list((m) = mean(b)), by = id]

The error I get is

Error: unexpected '=' in "test_dtb[ , list((m) =
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As mentioned in the comments by lukeA, setNames can be used:

m <- c("blah", "foo")
test_dtb[ , setNames(list(mean(b), median(b)), m), by = id] 

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

...