Change a dynamic variable name with rxSetVarInfo

妖精的绣舞 提交于 2019-12-11 08:08:32

问题


Trying to change a variable name of an XDF with rxSetVarInfo.

I want to merge several data sets with common var names. (I know rxMerge can/will append to filenames where needed. I want to have more control than that.)

This works:

outLetter<- "A"
exp <- list(pct.A = list(newName = paste0("X.pct.",outLetter)))
rxSetVarInfo(varInfo = exp, data = tempXDFFile)

That's where I know the original column name, pct.A. What if that's dynamic? What if this is in a function that gets called several times with different outLetter's. (The "A" isn't hardcoded.)
This does not work:

function(outLetter){
  exp <- list(paste0("pct.",outLetter) = list(newName = paste0("X.pct.",outLetter)))
  rxSetVarInfo(varInfo = exp, data = tempXDFFile)
}

Nor does:

exp <- parse(text = exp)
rxSetVarInfo(varInfo = exp, data = tempXDFFile)

Yes, I can hardcode all the permutations. Trying to find a more elegant approach.


回答1:


Please try this code:

dynamicName <- function(outLetter){
  exp <- vector(mode="list", length=1)
  names(exp) <- paste0("pct.",outLetter)
  exp[[paste0("pct.",outLetter)]] = list(newName = paste0("X.pct.",outLetter))
  rxSetVarInfo(varInfo = exp, data = tempXDFFile)
}

Before the call to rxSetVarInfo(), "exp" contains:

$pct.A
$pct.A$newName
[1] "X.pct.A"

Running your "this works" case, I see:

> outLetter<- "A"
> exp <- list(pct.A = list(newName = paste0("X.pct.",outLetter)))
>
> exp
$pct.A
$pct.A$newName
[1] "X.pct.A"

Hope this helps!

Note, please make sure that your dynamic naming function has access to the variable "tempXDFFile", you may want to consider passing it as a parameter, like:

dynamicName <- function(outLetter, data){
  exp <- vector(mode="list", length=1)
  names(exp) <- paste0("pct.",outLetter)
  exp[[paste0("pct.",outLetter)]] = list(newName = paste0("X.pct.",outLetter))
  rxSetVarInfo(varInfo = exp, data = data)
}


来源:https://stackoverflow.com/questions/43668701/change-a-dynamic-variable-name-with-rxsetvarinfo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!