cpr_tools optimisation

This commit is contained in:
AG Damsbo 2022-09-22 19:53:15 +02:00
parent 1220391510
commit 7321e2d8a9
12 changed files with 274 additions and 47 deletions

View File

@ -4,4 +4,5 @@ export(age_calc)
export(cpr_check)
export(cpr_dob)
export(cpr_female)
export(plot_ord_odds)
export(quantile_cut)

View File

@ -4,7 +4,7 @@
#' @param cpr cpr-numbers as ddmmyy[-.]xxxx or ddmmyyxxxx. Also mixed formatting. Vector or data frame column.
#' @keywords cpr
#'
#' @return Logical vector
#' @return Logical vector of cpr validity
#' @export
#'
#' @examples
@ -13,33 +13,26 @@
#' all(cpr_check(fsd))
cpr_check<-function(cpr){
# Check validity of CPR number, format ddmmyy-xxxx
# Build upon data from this document: https://cpr.dk/media/167692/personnummeret%20i%20cpr.pdf
# Build upon data from this document: https://cpr.dk/media/12066/personnummeret-i-cpr.pdf
## OBS according to new description, not all valid CPR numbers apply to this modulus 11 rule.
message(
"OBS: according to new description, not all valid CPR numbers apply to this modulus 11 rule.
Please refer to: https://cpr.dk/media/12066/personnummeret-i-cpr.pdf")
v <- c()
str_length <- nchar(cpr)
# Calculating length of each element in vector
for (i in seq_along(cpr)){
x <- cpr[i]
cpr_short <- paste0(substr(cpr,1,6),substr(cpr,str_length-3,str_length))
# Subsetting strings to first 6 and last 4 characters to short format cpr.
if (!substr(x,7,7)%in%c("-",".")){ # Added check to take p8 if ddmmyy[-.]xxxx,
x<-paste(substr(x,1,6),substr(x,7,10),collapse="-")
}
cpr_matrix <- matrix(as.numeric(unlist(strsplit(cpr_short,""))),nrow=10)
# Splitting all strings by each character to list, unlisting and creating matrix. Default is by column.
p1<-as.integer(substr(x,1,1))
p2<-as.integer(substr(x,2,2))
p3<-as.integer(substr(x,3,3))
p4<-as.integer(substr(x,4,4))
p5<-as.integer(substr(x,5,5))
p6<-as.integer(substr(x,6,6))
p7<-as.integer(substr(x,8,8))
p8<-as.integer(substr(x,9,9))
p9<-as.integer(substr(x,10,10))
p10<-as.integer(substr(x,11,11))
test_vector <- c(4,3,2,7,6,5,4,3,2,1)
# Multiplication vector from https://cpr.dk/media/12066/personnummeret-i-cpr.pdf
v[i] <- if((p1*4+p2*3+p3*2+p4*7+p5*6+p6*5+p7*4+p8*3+p9*2+p10) %% 11 == 0) TRUE else FALSE
}
return(v)
colSums(cpr_matrix*test_vector) %% 11 == 0
# Testing if modulus 11 == 0 of sums of matrix * multiplication vector.
}
#' Extracting date of birth from CPR
@ -57,28 +50,36 @@ cpr_check<-function(cpr){
#' cpr_dob(fsd)
cpr_dob<-function(cpr){
## Input as cpr-numbers in format ddmmyy-xxxx
## Build upon data from this document: https://cpr.dk/media/167692/personnummeret%20i%20cpr.pdf
## Build upon data from this document: https://cpr.dk/media/12066/personnummeret-i-cpr.pdf
dobs<-c()
a00<-as.numeric(c(0:99))
a36<-as.numeric(c(0:36))
a57<-as.numeric(c(0:57))
b00<-as.numeric(c(0,1,2,3))
b36<-as.numeric(c(4,9))
b57<-as.numeric(c(5,6,7,8))
a00<-c(0:99)
a36<-c(0:36)
a57<-c(0:57)
b00<-c(0:3)
b36<-c(4,9)
b57<-c(5:8)
str_length <- nchar(cpr)
# Calculating length of each element in vector
cpr_short <- paste0(substr(cpr,1,6),substr(cpr,str_length-3,str_length))
# Subsetting strings to first 6 and last 4 characters to short format cpr.
year <- as.numeric(substr(cpr_short,5,6))
ddmmyy <- as.Date(substr(cpr_short,1,6),format="%d%m%y")
for (i in seq_along(cpr)){
x <- cpr[i]
p56<-as.numeric(substr(x,5,6))
p56 <- year[i]
if (substr(x,7,7)%in%c("-",".")){
p8<-as.numeric(substr(x,8,8)) # Added check to take p8 if ddmmyy[-.]xxxx,
} else {p8<-as.numeric(substr(x,7,7))} # or p7 if ddmmyyxxxx
birth<-as.Date(substr(x,1,6),format="%d%m%y")
p8 <- substr(cpr_short[i],7,7)
# p8 is position 8 from the traditional cpr ddmmyy-xxxx, pos 7 in short version.
birth <- ddmmyy[i]
if (((p56%in%a00)&&(p8%in%b00)))
{
@ -100,7 +101,7 @@ cpr_dob<-function(cpr){
{
dob<-as.Date(format(birth, format="18%y%m%d"), format="%Y%m%d")
}
else {print("Input contains data in wrong format") # test if position 5,6 or 8 contains letters as is the case for temporary cpr-numbers
else {print("Input contains data in wrong format")
}
dobs[i]<-dob

56
R/plot_olr.R Normal file
View File

@ -0,0 +1,56 @@
#' Forrest plot from ordinal logistic regression.
#'
#' Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/
#'
#' @param x input data.
#' @param title plot title
#' @param dec decimals for labels
#' @param lbls labels for variable names. Carefull, as the right order is not checked automatically!
#' @param hori labels the horizontal axis (this i the y axis as the plot is rotated)
#' @param vert labels the horizontal axis (this i the x axis as the plot is rotated)
#' @param short flag to half number of ticks on horizontal axis.
#' @param input can be either "model", which is a olr model (polr()), or "df", which is a dataframe whith three columns for OR, lower CI and upper CI.
#'
#' @return gg object
#' @keywords forestplot
#' @export
plot_ord_odds<-function(x, title = NULL,dec=3,lbls=NULL,hori="OR (95 % CI)",vert="Variables",short=FALSE,input=c("model","df")){
require(ggplot2)
if (input=="model"){
odds<-data.frame(cbind(exp(coef(x)), exp(confint(x))))
}
if (input=="df"){
odds<-x
}
names(odds)<-c("or", "lo", "up")
rodds<-round(odds,digits = dec)
if (!is.null(lbls)){
odds$vars<-paste0(lbls," \n",paste0(rodds$or," [",rodds$lo,":",rodds$up,"]"))
}
else {
odds$vars<-paste0(row.names(odds)," \n",paste0(rodds$or," [",rodds$lo,":",rodds$up,"]"))
}
ticks<-c(seq(0, 1, by =.1), seq(1, 10, by =1), seq(10, 100, by =10))
if (short==TRUE){
ticks<-ticks[seq(1, length(ticks), 2)]
}
else {ticks<-ticks}
odds$ord<-c(nrow(odds):1)
ggplot(odds, aes(y= or, x = reorder(vars,ord))) +
geom_point() +
geom_errorbar(aes(ymin=lo, ymax=up), width=.2) +
scale_y_log10(breaks=ticks, labels = ticks) +
geom_hline(yintercept = 1, linetype=2) +
coord_flip() +
labs(title = title, x = vert, y = hori) +
theme_bw()
}

View File

@ -2,5 +2,5 @@ pandoc: 2.19.2
pkgdown: 2.0.6
pkgdown_sha: ~
articles: {}
last_built: 2022-09-22T13:44Z
last_built: 2022-09-22T17:52Z

View File

@ -73,11 +73,10 @@
<div class="section level2">
<h2 id="ref-examples">Examples<a class="anchor" aria-label="anchor" href="#ref-examples"></a></h2>
<div class="sourceCode"><pre class="sourceCode r"><code><span class="r-in"><span><span class="co"># Kim Larsen (cpr is known from album)</span></span></span>
<span class="r-in"><span> <span class="va">dob</span><span class="op">&lt;-</span><span class="fu">daDoctoR</span><span class="fu">::</span><span class="fu">dob_extract_cpr</span><span class="op">(</span><span class="st">"231045-0637"</span><span class="op">)</span></span></span>
<span class="r-err co"><span class="r-pr">#&gt;</span> <span class="error">Error in loadNamespace(x):</span> there is no package called daDoctoR</span>
<span class="r-in"><span> <span class="va">dob</span><span class="op">&lt;-</span><span class="fu">daDoctoR</span><span class="fu">::</span><span class="fu"><a href="https://rdrr.io/pkg/daDoctoR/man/dob_extract_cpr.html" class="external-link">dob_extract_cpr</a></span><span class="op">(</span><span class="st">"231045-0637"</span><span class="op">)</span></span></span>
<span class="r-in"><span> <span class="va">date</span><span class="op">&lt;-</span><span class="fu"><a href="https://rdrr.io/r/base/as.Date.html" class="external-link">as.Date</a></span><span class="op">(</span><span class="st">"2018-09-30"</span><span class="op">)</span></span></span>
<span class="r-in"><span> <span class="fu"><a href="https://rdrr.io/r/base/Round.html" class="external-link">trunc</a></span><span class="op">(</span><span class="fu">age_calc</span><span class="op">(</span><span class="va">dob</span>,<span class="va">date</span><span class="op">)</span><span class="op">)</span></span></span>
<span class="r-err co"><span class="r-pr">#&gt;</span> <span class="error">Error in age_calc(dob, date):</span> object 'dob' not found</span>
<span class="r-out co"><span class="r-pr">#&gt;</span> [1] 72</span>
</code></pre></div>
</div>
</main><aside class="col-md-3"><nav id="toc"><h2>On this page</h2>

View File

@ -55,15 +55,19 @@
<h2 id="value">Value<a class="anchor" aria-label="anchor" href="#value"></a></h2>
<p>Logical vector</p>
<p>Logical vector of cpr validity</p>
</div>
<div class="section level2">
<h2 id="ref-examples">Examples<a class="anchor" aria-label="anchor" href="#ref-examples"></a></h2>
<div class="sourceCode"><pre class="sourceCode r"><code><span class="r-in"><span><span class="va">fsd</span><span class="op">&lt;-</span><span class="fu"><a href="https://rdrr.io/r/base/c.html" class="external-link">c</a></span><span class="op">(</span><span class="st">"2310450637"</span>, <span class="st">"010115-4000"</span>, <span class="st">"0101896000"</span>,<span class="st">"010189-3000"</span>,<span class="st">"300450-1030"</span>,<span class="st">"010150-4021"</span><span class="op">)</span></span></span>
<span class="r-in"><span><span class="fu">cpr_check</span><span class="op">(</span><span class="va">fsd</span><span class="op">)</span></span></span>
<span class="r-msg co"><span class="r-pr">#&gt;</span> OBS: according to new description, not all valid CPR numbers apply to this modulus 11 rule. </span>
<span class="r-msg co"><span class="r-pr">#&gt;</span> Please refer to: https://cpr.dk/media/12066/personnummeret-i-cpr.pdf</span>
<span class="r-out co"><span class="r-pr">#&gt;</span> [1] TRUE FALSE FALSE FALSE FALSE FALSE</span>
<span class="r-in"><span><span class="fu"><a href="https://rdrr.io/r/base/all.html" class="external-link">all</a></span><span class="op">(</span><span class="fu">cpr_check</span><span class="op">(</span><span class="va">fsd</span><span class="op">)</span><span class="op">)</span></span></span>
<span class="r-msg co"><span class="r-pr">#&gt;</span> OBS: according to new description, not all valid CPR numbers apply to this modulus 11 rule. </span>
<span class="r-msg co"><span class="r-pr">#&gt;</span> Please refer to: https://cpr.dk/media/12066/personnummeret-i-cpr.pdf</span>
<span class="r-out co"><span class="r-pr">#&gt;</span> [1] FALSE</span>
</code></pre></div>
</div>

View File

@ -67,6 +67,11 @@
<dd>Determine female sex from CPR</dd>
</dl><dl><dt>
<code><a href="plot_ord_odds.html">plot_ord_odds()</a></code>
</dt>
<dd>Forrest plot from ordinal logistic regression.</dd>
</dl><dl><dt>
<code><a href="quantile_cut.html">quantile_cut()</a></code>
</dt>
<dd>Easy function for splitting numeric variable in quantiles</dd>

View File

@ -0,0 +1,117 @@
<!DOCTYPE html>
<!-- Generated by pkgdown: do not edit by hand --><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content="Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/"><title>Forrest plot from ordinal logistic regression. — plot_ord_odds • stRoke</title><script src="../deps/jquery-3.6.0/jquery-3.6.0.min.js"></script><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><link href="../deps/bootstrap-5.1.3/bootstrap.min.css" rel="stylesheet"><script src="../deps/bootstrap-5.1.3/bootstrap.bundle.min.js"></script><!-- Font Awesome icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css" integrity="sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=" crossorigin="anonymous"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css" integrity="sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=" crossorigin="anonymous"><!-- bootstrap-toc --><script src="https://cdn.rawgit.com/afeld/bootstrap-toc/v1.0.1/dist/bootstrap-toc.min.js"></script><!-- headroom.js --><script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/headroom.min.js" integrity="sha256-AsUX4SJE1+yuDu5+mAVzJbuYNPHj/WroHuZ8Ir/CkE0=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/jQuery.headroom.min.js" integrity="sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=" crossorigin="anonymous"></script><!-- clipboard.js --><script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js" integrity="sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=" crossorigin="anonymous"></script><!-- search --><script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/6.4.6/fuse.js" integrity="sha512-zv6Ywkjyktsohkbp9bb45V6tEMoWhzFzXis+LrMehmJZZSys19Yxf1dopHx7WzIKxr5tK2dVcYmaCk2uqdjF4A==" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/autocomplete.js/0.38.0/autocomplete.jquery.min.js" integrity="sha512-GU9ayf+66Xx2TmpxqJpliWbT5PiGYxpaG8rfnBEk1LL8l1KGkRShhngwdXK1UgqhAzWpZHSiYPc09/NwDQIGyg==" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js" integrity="sha512-5CYOlHXGh6QpOFA/TeTylKLWfB3ftPsde7AnmhuitiTX4K5SqCLBeKro6sPS8ilsz1Q4NRx3v8Ko2IBiszzdww==" crossorigin="anonymous"></script><!-- pkgdown --><script src="../pkgdown.js"></script><meta property="og:title" content="Forrest plot from ordinal logistic regression. — plot_ord_odds"><meta property="og:description" content="Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/"><!-- mathjax --><script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" integrity="sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js" integrity="sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=" crossorigin="anonymous"></script><!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]--></head><body>
<a href="#main" class="visually-hidden-focusable">Skip to contents</a>
<nav class="navbar fixed-top navbar-light navbar-expand-lg bg-light"><div class="container">
<a class="navbar-brand me-2" href="../index.html">stRoke</a>
<small class="nav-text text-muted me-auto" data-bs-toggle="tooltip" data-bs-placement="bottom" title="">0.22.9.2</small>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div id="navbar" class="collapse navbar-collapse ms-3">
<ul class="navbar-nav me-auto"><li class="active nav-item">
<a class="nav-link" href="../reference/index.html">Reference</a>
</li>
</ul><form class="form-inline my-2 my-lg-0" role="search">
<input type="search" class="form-control me-sm-2" aria-label="Toggle navigation" name="search-input" data-search-index="../search.json" id="search-input" placeholder="Search for" autocomplete="off"></form>
<ul class="navbar-nav"></ul></div>
</div>
</nav><div class="container template-reference-topic">
<div class="row">
<main id="main" class="col-md-9"><div class="page-header">
<img src="" class="logo" alt=""><h1>Forrest plot from ordinal logistic regression.</h1>
<div class="d-none name"><code>plot_ord_odds.Rd</code></div>
</div>
<div class="ref-description section level2">
<p>Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/</p>
</div>
<div class="section level2">
<h2 id="ref-usage">Usage<a class="anchor" aria-label="anchor" href="#ref-usage"></a></h2>
<div class="sourceCode"><pre class="sourceCode r"><code><span><span class="fu">plot_ord_odds</span><span class="op">(</span></span>
<span> <span class="va">x</span>,</span>
<span> title <span class="op">=</span> <span class="cn">NULL</span>,</span>
<span> dec <span class="op">=</span> <span class="fl">3</span>,</span>
<span> lbls <span class="op">=</span> <span class="cn">NULL</span>,</span>
<span> hori <span class="op">=</span> <span class="st">"OR (95 % CI)"</span>,</span>
<span> vert <span class="op">=</span> <span class="st">"Variables"</span>,</span>
<span> short <span class="op">=</span> <span class="cn">FALSE</span>,</span>
<span> input <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html" class="external-link">c</a></span><span class="op">(</span><span class="st">"model"</span>, <span class="st">"df"</span><span class="op">)</span></span>
<span><span class="op">)</span></span></code></pre></div>
</div>
<div class="section level2">
<h2 id="arguments">Arguments<a class="anchor" aria-label="anchor" href="#arguments"></a></h2>
<dl><dt>x</dt>
<dd><p>input data.</p></dd>
<dt>title</dt>
<dd><p>plot title</p></dd>
<dt>dec</dt>
<dd><p>decimals for labels</p></dd>
<dt>lbls</dt>
<dd><p>labels for variable names. Carefull, as the right order is not checked automatically!</p></dd>
<dt>hori</dt>
<dd><p>labels the horizontal axis (this i the y axis as the plot is rotated)</p></dd>
<dt>vert</dt>
<dd><p>labels the horizontal axis (this i the x axis as the plot is rotated)</p></dd>
<dt>short</dt>
<dd><p>flag to half number of ticks on horizontal axis.</p></dd>
<dt>input</dt>
<dd><p>can be either "model", which is a olr model (polr()), or "df", which is a dataframe whith three columns for OR, lower CI and upper CI.</p></dd>
</dl></div>
<div class="section level2">
<h2 id="value">Value<a class="anchor" aria-label="anchor" href="#value"></a></h2>
<p>gg object</p>
</div>
</main><aside class="col-md-3"><nav id="toc"><h2>On this page</h2>
</nav></aside></div>
<footer><div class="pkgdown-footer-left">
<p></p><p>Developed by Andreas Gammelgaard Damsbo.</p>
</div>
<div class="pkgdown-footer-right">
<p></p><p>Site built with <a href="https://pkgdown.r-lib.org/" class="external-link">pkgdown</a> 2.0.6.</p>
</div>
</footer></div>
</body></html>

File diff suppressed because one or more lines are too long

View File

@ -27,6 +27,9 @@
<url>
<loc>/reference/index.html</loc>
</url>
<url>
<loc>/reference/plot_ord_odds.html</loc>
</url>
<url>
<loc>/reference/quantile_cut.html</loc>
</url>

View File

@ -10,7 +10,7 @@ cpr_check(cpr)
\item{cpr}{cpr-numbers as ddmmyy\link{-.}xxxx or ddmmyyxxxx. Also mixed formatting. Vector or data frame column.}
}
\value{
Logical vector
Logical vector of cpr validity
}
\description{
Checking validity of cpr number. Vectorised.

41
man/plot_ord_odds.Rd Normal file
View File

@ -0,0 +1,41 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_olr.R
\name{plot_ord_odds}
\alias{plot_ord_odds}
\title{Forrest plot from ordinal logistic regression.}
\usage{
plot_ord_odds(
x,
title = NULL,
dec = 3,
lbls = NULL,
hori = "OR (95 \% CI)",
vert = "Variables",
short = FALSE,
input = c("model", "df")
)
}
\arguments{
\item{x}{input data.}
\item{title}{plot title}
\item{dec}{decimals for labels}
\item{lbls}{labels for variable names. Carefull, as the right order is not checked automatically!}
\item{hori}{labels the horizontal axis (this i the y axis as the plot is rotated)}
\item{vert}{labels the horizontal axis (this i the x axis as the plot is rotated)}
\item{short}{flag to half number of ticks on horizontal axis.}
\item{input}{can be either "model", which is a olr model (polr()), or "df", which is a dataframe whith three columns for OR, lower CI and upper CI.}
}
\value{
gg object
}
\description{
Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/
}
\keyword{forestplot}