动态(在i,j和by中)分配/引用data.table中的列名 [英] Assigning/Referencing a column name in data.table dynamically (in i, j and by)

查看:66
本文介绍了动态(在i,j和by中)分配/引用data.table中的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A)代替此(其中 cars<-data.table(cars)

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

我需要这个

  strColumnName<-总计: 
汽车[,strColumnName =。 N,按=速度]

该怎么做?



B)同样(更一般的情况)-代替此:

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

我需要这个:

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



<这个问题是关于在data.table中动态分配/引用列名变量的一般方式,即在 j(RHS和LHS)以及 i和 by中动态分配/引用。



C



C)在涉及代码i,j和by的一般情况下-而不是在此选择:

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

我需要这个:

  strFactor<- dist; 
strNewVariable<-总计x因子:
strBy<-速度
汽车[strFactor> 50,。(strNewVariable = .N * strFactor),by = strBy]


解决方案

编辑:
根据您的说明,下面是使用 setNames get的方法。这里的技巧是 .. 指示评估在调用环境中进行。

 库(data.table)
汽车<--data.table(汽车)
strFactor< ;- dist
strNewVariable<-总计x因子:
strBy<-速度
cars [get(strFactor)> 50,
setNames(。(。N * get(.. strFactor)),strNewVariable),
by = strBy]


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] 

解决方案

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] 

这篇关于动态(在i,j和by中)分配/引用data.table中的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆