r - 如何洗牌表示为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 中划分数值函数。
解决方案
目前尚不清楚您的“统一法律”有多“通用”。您似乎想在多项式表达式中分隔元素。假设并假设简单函数中的其他所有内容都无关紧要,这将作为一个起点:
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
变量如何,但从上面您可以修改以获得您想要的。
推荐阅读
- python - 您如何处理时间序列分析中的零点?
- visual-studio - 如何在 Visual Studio(2019 或更高版本)中从 .vscode/tasks.json 运行任务
- php - 从 WooCommerce 订阅仪表板中删除特定用户角色的操作按钮
- reactjs - 如何在 MERN 中使用 params 发布和获取数据
- c# - 使用oledb将数据导出到excel
- javascript - JS - 重复数组项并在循环中重复更改值
- ros - 如何修改 Gazebo 插件,使其不仅适用于世界文件,还适用于 URDF 文件?
- android - 带有导航组件的 Fragment 中的 BottomNavigation
- python - 计算成绩并分配给每个学生
- c++ - 如何使用多维初始化列表初始化自定义容器?