Change a dynamic variable name with rxSetVarInfo

2019-08-03 05:15发布

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.

标签: microsoft-r
1条回答
淡お忘
2楼-- · 2019-08-03 06:06

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)
}
查看更多
登录 后发表回答