将代码转换为 R 中的函数

2024-01-06

我有一系列的步骤,我想将它们转换为函数,因此我只需通过调用它们即可将其应用于数据框。下面是带有一些注释的代码:

library("textreadr")
library("pdftools")   
library("tidyverse")
library("tidytext")    
library("textreadr")
library("tm")

# Create Data frame
Off_let_data <- data.frame(page_id = c(3,3,3,3,3), element_id = c(19, 22, 26, 31, 31), 
                                 text = c("The Protected Percentage of your property value thats has been chosen is 0%", 
                                          "The Arrangement Fee payable at complettion: £50.00", 
                                          "The Fixed Interest Rate that is applied for the life of the period is: 5.40%", 
                                          "The Benchmark rate that will be used to calculate any early repayment 2.08%", 
                                          "The property value used in this scenario is 275,000.00"))

# read in the first element of a list of pdf file from a folder
files <- list.files(pattern = "pdf$")[1]

# extract the account number from the first pdf file
acc_num <- str_extract(files, "^\\d+")

# The RegEx's used to extract the relevant information
protec_per_reg <- "Protected\\sP\\w+\\sof"
Arr_Fee_reg <- "^The\\sArrangement\\sF\\w+"
Fix_inter_reg <- "Fixed\\sI\\w+\\sR\\w+"
Bench_rate_reg <- "Benchmark\\sR\\w+\\sthat"

# create a df that only includes the rows which match the above RegEx
Off_let <- Off_let_data %>% filter(page_id == 3, str_detect(Off_let_data$text, protec_per_reg)|
                                     str_detect(Off_let_data$text, Arr_Fee_reg) | str_detect(Off_let_data$text, Fix_inter_reg) | 
                                     str_detect(Off_let_data$text, Bench_rate_reg))

# Now only extract the numbers from the above DF
off_let_num <- str_extract(Off_let$text, "\\d+\\.?\\d+")

# The first element is always a NA value - based on the structure of these PDF files
# replace the first element of this character vector with the below
off_let_num[is.na(off_let_num)] <- str_extract(Off_let$text, "\\d+%")[[1]] 
off_let_num

有人可以帮我把它变成一个函数吗?谢谢


像这样的东西吗?

函数的输入/输出应该是什么?目前,该函数仅接受 data.frame 作为唯一参数,但您可以扩展它,以便您可以传递不同的正则表达式,或者定义 page_id 例如。

library("textreadr")
library("pdftools")   
library("tidyverse")
library("tidytext")    
library("textreadr")
library("tm")

# Create Data frame
Off_let_data <- data.frame(page_id = c(3,3,3,3,3), element_id = c(19, 22, 26, 31, 31), 
                           text = c("The Protected Percentage of your property value thats has been chosen is 0%", 
                                    "The Arrangement Fee payable at complettion: £50.00", 
                                    "The Fixed Interest Rate that is applied for the life of the period is: 5.40%", 
                                    "The Benchmark rate that will be used to calculate any early repayment 2.08%", 
                                    "The property value used in this scenario is 275,000.00"))

dummyFunc <- function(df) {
  # read in the first element of a list of pdf file from a folder
  files <- list.files(pattern = "pdf$")[1]

  # extract the account number from the first pdf file
  acc_num <- str_extract(files, "^\\d+")

  # The RegEx's used to extract the relevant information
  protec_per_reg <- "Protected\\sP\\w+\\sof"
  Arr_Fee_reg <- "^The\\sArrangement\\sF\\w+"
  Fix_inter_reg <- "Fixed\\sI\\w+\\sR\\w+"
  Bench_rate_reg <- "Benchmark\\sR\\w+\\sthat"

  # create a df that only includes the rows which match the above RegEx
  Off_let <- df %>% filter(page_id == 3, str_detect(df$text, protec_per_reg)|
                                       str_detect(df$text, Arr_Fee_reg) | str_detect(df$text, Fix_inter_reg) | 
                                       str_detect(df$text, Bench_rate_reg))

  # Now only extract the numbers from the above DF
  off_let_num <- str_extract(Off_let$text, "\\d+\\.?\\d+")

  # The first element is always a NA value - based on the structure of these PDF files
  # replace the first element of this character vector with the below
  off_let_num[is.na(off_let_num)] <- str_extract(Off_let$text, "\\d+%")[[1]] 
  return(off_let_num)
}

dummyFunc(Off_let_data)

对于该函数的更扩展版本:

# The RegEx's used to extract the relevant information
protec_per_reg <- "Protected\\sP\\w+\\sof"
Arr_Fee_reg <- "^The\\sArrangement\\sF\\w+"
Fix_inter_reg <- "Fixed\\sI\\w+\\sR\\w+"
Bench_rate_reg <- "Benchmark\\sR\\w+\\sthat"

regexprlist <- list(protec_per_reg, Arr_Fee_reg,
                    Fix_inter_reg, Bench_rate_reg)

dummyFuncExt <- function(df, regexp, page_id) {
  # read in the first element of a list of pdf file from a folder
  files <- list.files(pattern = "pdf$")[1]

  # extract the account number from the first pdf file
  acc_num <- str_extract(files, "^\\d+")

  # create a df that only includes the rows which match the above RegEx
  Off_let <- df %>% filter(page_id == page_id, str_detect(df$text, regexprlist[[1]])|
                             str_detect(df$text, regexprlist[[2]]) | str_detect(df$text, regexprlist[[3]]) | 
                             str_detect(df$text, regexprlist[[4]]))

  # Now only extract the numbers from the above DF
  off_let_num <- str_extract(Off_let$text, "\\d+\\.?\\d+")

  # The first element is always a NA value - based on the structure of these PDF files
  # replace the first element of this character vector with the below
  off_let_num[is.na(off_let_num)] <- str_extract(Off_let$text, "\\d+%")[[1]] 
  return(off_let_num)
}

dummyFuncExt(df = Off_let_data, regexp = regexprlist, page_id = 3)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将代码转换为 R 中的函数 的相关文章

  • R:ifelse 中的字符串列表

    我正在寻找与 MySQL 中的 where var in 语句类似的东西 我的代码如下 data lt data frame id 10001 10030 cc1 rep c a b c 10 attach data data new lt
  • [Regex]::Replace() 和 -replace 有什么区别?

    我明白了之间的区别 Replace and replace 但是什么是 replace and Regex Replace 我测试了以下两个代码 但对我来说结果完全相同 我还提到了 PowerShell Cookbook O reilly
  • 正则表达式验证字符串是否包含三个非空白字符

    我使用欧芹 js 来验证输入 并且使用 data parsley pattern 它允许我传递正则表达式 我正在尝试验证该字符串以确保它至少包含三个非空白字符 下面是应该无效或有效的字符串 valid 1 2 b invalid 1 b s
  • Python re无限执行

    我正在尝试执行这段代码 import re pattern r w w s re compiled re compile pattern results re compiled search COPRO HORIZON 2000 HOR p
  • zsh:未找到命令:使用 Big Sur Mac 的终端上的 R

    我从官方 cran 网站安装了 R 我可以从 Rstudio 运行 R 但是当我尝试从终端使用 R 时 我得到以下结果 base ege Eges MBP R zsh command not found R base ege Eges MB
  • 通过 r markdown 中的循环创建代码片段

    如同如何使用R中的knitr创建一个包含代码块和文本的循环 https stackoverflow com questions 36373630 how to create a loop that includes both a code
  • REGEXP_REPLACE - 仅当包含在 () 中时才从字符串中删除逗号

    我在 oracle 论坛网站找到了一个例子 输入字符串 a b c x y z a xx yy zz x WITH t AS SELECT a b c x y z a xx yy zz x col1 FROM dual SELECT t c
  • 为正则表达式编写解析器

    即使经过多年的编程 我很羞愧地说我从未真正完全掌握正则表达式 一般来说 当问题需要正则表达式时 我通常可以 在一堆引用语法之后 想出一个合适的正则表达式 但我发现自己越来越频繁地使用这种技术 所以 自学并理解正则表达式properly 我决
  • R data.table fwrite 到 fread 空间分隔符并清空

    我在使用 fread 以 作为分隔符和散布的空白值时遇到问题 例如 这个 dt lt data table 1 5 1 5 1 5 make a simple table dt 3 V2 NA add a blank in the midd
  • rvest 和 NHL 统计数据的 CSS 选择器问题

    我想从 hockey reference com 中抓取数据 特别是从以下链接中抓取数据 https www hockey reference com leagues NHL 1991 html https www hockey refer
  • 更改 pander 中的默认对齐方式 (pandoc.table)

    我目前正在切换到pander对于我的大部分时间knitr markdown格式化 因为它提供了如此出色的pandoc支持 我不太满意的一件事是默认的居中对齐 营销人员可能会喜欢它 但对于技术报告来说这是一个可怕的事情 使用的最佳选择Hmis
  • 使用 ggplot 构面时增加闪亮的绘图大小

    有没有办法增加绘图窗口的大小shiny取决于在一个中使用的面的数量ggplot图 也许使用垂直滚动 例如 使用下面的示例 当输入为 A 有三个方面 情节看起来不错 当选项 B 选择绘图数量会增加 但绘图窗口保持相同大小 导致绘图太小 是否有
  • 汇总表中各列的字符值比例

    在这种数据框中 df lt data frame w1 c A A B C A w2 c C A A C C w3 c C A B C B 我需要计算所有列中字符值的列内比例 有趣的是 以下代码适用于大型实际数据集 但对上述玩具数据会引发错
  • R 中的龙卷风图

    我正在尝试在 R 中绘制龙卷风图 又名敏感性图 目标是可视化某些变量增加 10 和减少 10 的效果 到目前为止我已经得到这个结果 这是我正在使用的代码 Tornado plot data lt matrix c 0 02 0 02 0 0
  • 使用 RDCOMClient 搜索 Outlook 收件箱

    我尝试使用 RDCOMClient 在 Outlook 收件箱中搜索电子邮件中的特定主题 然后获取附件 我在一封电子邮件上进行了这项工作 但由于主题包含日期元素 我需要搜索成为一个类似的子句 但不太清楚这适合我的下面的查询 outlook
  • 使用 pkg:sjPlot 函数创建一个生成部分斜体单元格的数据框

    我正在尝试创建一个简单的数据表 其中 Coral taxon 列中的属名称为斜体 而 spp 列中的属名称为斜体 属名后面的部分不大写 我尝试使用 expression 函数对 Coral taxon 的每一行进行编码 但没有成功 sum
  • PHP 中的 Preg_replace

    我想替换 中包含的字符串中的内容content 它是多行等 preg replace 函数应该删除整个 com 没有垫子 蒙特 尝试这个 result preg replace s replacement content subject
  • 在 igraph 中为社区分配颜色

    我在 igraph 中使用 fastgreedy community 检测算法在 R 中生成社区 代码返回 12 个社区 但是在绘图时很难识别它们 因为它返回的图的颜色数量有限 我怎样才能用十二种不同的颜色绘制这个图表 l2 lt layo
  • 如何自动启动我的 ec2 实例、运行命令然后将其关闭?

    我想每周对 redshift postgres 数据库中的数据运行一次机器学习模型 我使用以下命令将 R 脚本设置为休息 apiplumbr然后我将其设置为一项任务来管理pm2 我有它 所以任务会在ec2实例启动然后继续运行 要让 R 脚本
  • 计算互相关函数?

    In R 我在用ccf or acf计算成对互相关函数 以便我可以找出哪个移位给我带来最大值 从它的外观来看 R给我一个标准化的值序列 Python 的 scipy 中是否有类似的东西 或者我应该使用fft模块 目前 我正在这样做 xcor

随机推荐

  • iOS - 链接器错误、重复符号

    似乎我在尝试编译时遇到错误 它似乎直接指向两个文件 MenuViewController 和 FirstTopViewController 我认为这与我的导入有关 因为它们每个都在导入另一个 但是错误引用了我的 Building 对象 该对
  • 打瞌睡模式和应用程序待机

    我如何在我的应用程序中知道手机是否处于打瞌睡模式或我的应用程序是否处于待机模式 我也可以通过某种订阅方式知道吗 有一个区别应用程序待机 您的应用程序转到的位置 睡觉是因为很孤独 和Doze 系统去哪里 睡觉 因为用户有生命 Doze仅当您的
  • 使用 Dapper 映射 SqlGeography

    我有实体 Point 其中包含 ID 文本和地理坐标 CREATE TABLE Point Id INT IDENTITY CONSTRAINT PK Point Id PRIMARY KEY Coords GEOGRAPHY NOT NU
  • android ConstraintLayout 不允许负边距

    我相对于布局指南放置了很多项目 并希望将新项目放置在几乎与此布局指南相关的位置 我尝试使用负布局边距但没有成功 android translationX 10dp android translationY 10dp
  • Laravel:使用 AJAX 请求渲染部分视图

    我正在尝试制作一个单页 CRUD 应用程序 并且将 AJAX 与 jQuery 结合使用 在本例中 我提交表单并在数据库中异步存储一个新国家 地区 然后使用新数据渲染部分视图 这是我的脚本和从数据库检索国家 地区并返回部分视图的方法 cre
  • 写入错误:使用 O_DIRECT 打开文件时参数无效

    对我来说 用以下内容写入文件非常重要O DIRECT flag 这就是我打开文件的方式 Open the file int fd if fd open inFilepath O WRONLY O CREAT O SYNC O DIRECT
  • 在表达式中的 let .. 中使用守卫

    有时我会写这样的代码 solveLogic Int gt Int gt Int solveLogic a b let x 1 brainiac a gt x 1 a b 333 otherwise 5 in brainiac 每次我都想写这
  • IPython Notebook 之前的单元格内容

    是否可以在 IPython Notebook 单元格中获取上一个 上方 单元格内容 我可以使用 capture 魔术函数查看以前的输出 但我不知道如何获取以前的单元格内容 recall jupyter notebook cell numbe
  • 普通 Javascript 对象上的 jQuery.bind() 事件

    是否可以将 jQuery 事件绑定到普通的非 DOM Javascript 对象 var myobject myobject bind foobar function alert daa myobject trigger foobar 有何
  • 如何让下面的代码更快

    int u1 u2 unsigned long elm1 20 mulpre 16 20 res1 40 res2 40 64 bits long res1 res2 initialized to zero l 60 while l for
  • PHP Array_intersect 在具有未知数量键的多维数组上

    我正在尝试在拥有资源 人员 的应用程序中制作高级搜索过滤器 我在 1 个多维数组中得到了所有结果 该应用程序的用户可以搜索人员的职位名称 技能 工作领域和国家 地区 我已经完成了查找符合用户给出的标准的人的部分 这些结果存储在多维数组中 如
  • Android ACTION_GET_CONTENT 不更新下载目录文件

    我在选择文件时遇到问题下载目录使用ACTION 获取 内容 如果我删除本地存储中的 ES 资源管理器或文件管理器中的任何文件 这些删除的文件不会在下载在我的应用程序中打开时的目录 任何变化下载dir 没有反映在选择器中 要选择一个文件 我正
  • Angular 通用 html lang 标签

    在 Angular Universal 中 我有一个 index html 文件 顶部有 我想根据我所在的页面更改此设置 maldonadoattorney com es jailreleases 将是 maldonadoattorney
  • Django - 使用模板标签和“with”?

    我有一个自定义模板标签 def uploads for user user uploads Uploads objects filter uploaded by user problem upload False num uploads u
  • 基于支持向量的数据重采样器

    我正在努力实现一个数据重采样器以基于support vectors 这个想法是为了适应SVM分类器 得到support vector类的点 然后通过仅选择每个类的支持向量点附近的数据点来平衡数据 以使类具有相同数量的示例 忽略所有其他 远离
  • Google Plus API 错误gapi.loaded_0

    我尝试将 requireJS 与 Google plus API 一起使用 但是当我单击登录按钮时出现错误 这是错误和屏幕截图 GET https apis google com scs apps static js k oz gapi e
  • 如何在pytorch中使用LSTM进行分类?

    我的代码如下 class Mymodel nn Module def init self input size hidden size output size num layers batch size super Discriminato
  • 在非活动类中显示进度对话框

    我正在尝试在非活动类中显示对话框 基本上 我在我的应用程序中检测到一个对象 我想显示一个对话框 然后切换活动 我在 logcat 中收到 java lang RuntimeException 无法在未调用 Looper prepare 的线
  • 链接方法时如何返回 false

    我有一个使用方法链的验证类 我希望能够进行单次检查TRUE FALSE像这样 if obj gt checkSomething 但也有像这样的链方法 if obj gt checkSomething gt checkSomethingEls
  • 将代码转换为 R 中的函数

    我有一系列的步骤 我想将它们转换为函数 因此我只需通过调用它们即可将其应用于数据框 下面是带有一些注释的代码 library textreadr library pdftools library tidyverse library tidy