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

r - Assigning/Referencing a column name in data.table dynamically (in i, j and by)

A) Instead of this (where cars <- data.table(cars))

cars[ , .(`Totals:`=.N), by=speed]  

I need this

strColumnName <- "Totals:"
cars [ , strColumnName = .N, by=speed]  

How to do it?

B) Similarly (more general case) - instead of this:

cars[ dist > 50, .(`Totals:`=.N, x=dist*100), by=speed] 

I need this:

strFactor <- "dist"
cars[ strFactor > 50, .(`Totals:`=.N, x=strFactor*100), by=speed] 

This question is about GENERAL way of assigning/referencing column name variables in data.table, i.e. in 'j' (both RHS and LHS), as well as in 'i' and 'by' - dynamically. This is needed when are chosen elsewhere in the code (e.g. a user my enter them in shiny app)

C) General case involving i,j and by - Instead of this:

 cars[ dist > 50, .(`Totals x Factor: ` = .N * dist), by=speed] 

I need this:

strFactor <- "dist"; 
strNewVariable <- "Totals x Factor: "
strBy <- "speed"
cars[ strFactor > 50, .(strNewVariable = .N * strFactor), by=strBy] 
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Edit: Based on your clarifications, here is an approach with setNames and get. The trick here is that .. instructs the evaluation to occur in the calling environment.

library(data.table)
cars <- data.table(cars)
strFactor <- "dist"
strNewVariable <- "Totals x Factor: "
strBy <- "speed"
cars[ get(strFactor)  > 50, 
     setNames(.(.N * get(..strFactor)),strNewVariable),
     by=strBy] 

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

...