首页 > 解决方案 > 如何洗牌表示为R中总和的函数的一部分?

问题描述

如果我在 R 中有任何数值函数,例如:

objFun=function(x) return(x^2+x+1) 

如何使用统一的法则对 R 中任何函数的部分进行洗牌?

例子 :

“objFun”的部分是 x^2 & x & 1。

首先我需要检索 n=3 的组件数,然后我应该将 x^2 & x & 1 存储在维度 = 3 的表中。

之后,我可以将这些部分存储在变量 tmp 中,例如:

if (uniform law return 1 ) then : tmp= x^2
if (uniform law return 2 ) then : tmp= x
if (uniform law return 3)  then : tmp= 1

我没有尝试,因为我不知道如何在 R 中划分数值函数。

标签: r

解决方案


目前尚不清楚您的“统一法律”有多“通用”。您似乎想在多项式表达式中分隔元素。假设并假设简单函数中的其他所有内容都无关紧要,这将作为一个起点:

objFun=function(x) return(x^2+x+1) 
objFun

functionElements <- function(fn) {
  # Regular expression of the function body
  # Remove anything ahead of an open parenthesis (
  # Remove anything after a close parenthesis )
  # split on the 4 main arithmetic functions, +, -, * and /
  # double backslash means "match the next character exactly", since +, *, -, / have regular expression meanings
  # | means "or"
  splitElements <- strsplit(split = ".*\\(|\\+|\\*| |\\).*|\\/|\\-", deparse(body(fn)))[[1]]
  # remove empty parts ('non zero character')
  splitElements <- splitElements[nzchar(splitElements)]
  splitElements
}

functionElements(objFun)

目前尚不清楚您希望tmp变量如何,但从上面您可以修改以获得您想要的。


推荐阅读