{"id":4725,"date":"2022-08-24T02:43:28","date_gmt":"2022-08-23T21:13:28","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/"},"modified":"2022-08-24T02:43:28","modified_gmt":"2022-08-23T21:13:28","slug":"solved-extract-components-of-strings-and-fill-down-where-missing-in-r","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/","title":{"rendered":"[Solved] Extract components of strings and fill-down where missing in R"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-68650535\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"68650535\" data-parentid=\"68637196\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Based on the discussion in the comments it appears that it is not feasible to construct a key for <code>joining<\/code> the <code>Species_name<\/code> with a <code>look-up<\/code> table.<\/p>\n<p>What you could do is determine the &#8220;similarity&#8221; of your (species) names with such a look-up table. This assumes that your (species) names are different enough. To determine the &#8220;similarity&#8221; or better the &#8220;distance&#8221; of the strings (your names), we use the package <code>{stringdist}<\/code>.<br \/>\nThere are many string-(dis)similarity algorithms. For the example below, I work on the basis that your (species) names begin in a similar way. (Note: you may have to ensure this or use another algorithm for the distance measure).<\/p>\n<p>You did not provide a fully reproducible example. I construct an example input tibble based on your question and derive the look-up vector from this tibble. You may be able to extract the look-up from your data in another manner.<\/p>\n<p><strong>prep work<\/strong><\/p>\n<pre><code>library(dplyr)                     # for data crunching\n# install.packages(\"stringdist\")   # install from CRAN\nlibrary(stringdist)                # use stringdist\n\n# emulate example\ninput &lt;- tibble::tribble(\n   ~SEQ, ~Species_name\n    , 1, \"Aglaia lawii\"\n    , 2, \"Aglaia lawii\"\n    , 2, \"Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy\"\n    , 3, \"Alangium uniloculare\"\n    , 4, \"Alangium uniloculare (Griff.) King\"\n   )\n\n# create a look-up vector of all \"full names\"\nlookup &lt;- input %&gt;% \n   filter(grepl(pattern = \".\\\\(\"    # checking for the opening bracket\n                , x = Species_name)\n   ) %&gt;% \n   pull(Species_name)               # keep the names column as look-up vector\n<\/code><\/pre>\n<p><strong>string (dis)similarity<\/strong><\/p>\n<p>There are many algorithm to determine the (dis)similarity of strings. The <code>{stringdist}<\/code> package offers some. There exists a function that provides a <code>distance<\/code>. Without going in too much details, think about distance being the number of operations required to turn a string into one of the lookup strings. For more details, read up in the documentation. The different algorithm consider different ways of doing these transformations (and many things more). The <code>Jaro-Winkler<\/code> algorithm gives a preference to strings that match from the beginning.<\/p>\n<p>Let&#8217;s check what the Jaro-Winkler <code>jw<\/code> (method) implementation in <code>{stringdist}<\/code> works:<\/p>\n<pre><code>stringdist(input$Species_name[1], lookup, method = \"jw\")\n[1] 0.2500000 0.3908497\n<\/code><\/pre>\n<p>From this we can derive that the first element of our lookup is similar (lower distance) and starts similarly than <code>Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy<\/code>.<\/p>\n<p><strong>iterating over our tibble and replace\/identify the best full names<\/strong><\/p>\n<p>As we work with a tibble of species names, we need to compare the actual species names with the look-up vector. To iterate over the different rows we use <code>{purrr}<\/code> and apply the (dis)similarity comparison.<br \/>\nFor the latter we construct a short function to make this more compact.<\/p>\n<p>Note: The <code>lookup<\/code> was created above based on the example data. This might however come from elsewhere.<\/p>\n<pre><code>library(purrr)\n\nbest_guess_full_name &lt;- function(.df, .options = lookup){\n#----- best guess bg picks from options look-up the most similar (:= min dissimilar)\n    bg &lt;- .options[which.min(stringdist(.df$Species_name, .options, method = \"jw\"))]\n#------ append the \"best guess\" to the row (dataframe) and return\n    df &lt;- .df %&gt;% mutate(Full_species = bg)\n}\n<\/code><\/pre>\n<p>Let&#8217;s test the function taking the 2nd row of input (i.e. input[2, ]).<br \/>\nNote: the brackets around the call will print the result, since we do not use return in our function.<\/p>\n<pre><code>( input[2,] %&gt;% best_guess_full_name() )\n# A tibble: 1 x 3\n    SEQ Species_name Full_species                                    \n  &lt;dbl&gt; &lt;chr&gt;        &lt;chr&gt;                                           \n1     2 Aglaia lawii Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy\n<\/code><\/pre>\n<p><strong>putting it all together<\/strong><\/p>\n<p>With this we can now process (iterate over each row) the input dataframe\/tibble and return in as a dataframe\/tibble.<\/p>\n<pre><code>input %&gt;% \n   split(row.names(authors)) %&gt;%              # creates a list, each row a data frame\n   purrr::map_dfr(.f = best_guess_full_name)  # iterate over every list element (row dataframe)\n\n# A tibble: 5 x 3\n    SEQ Species_name                                     Full_species                                    \n  &lt;dbl&gt; &lt;chr&gt;                                            &lt;chr&gt;                                           \n1     1 Aglaia lawii                                     Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy\n2     2 Aglaia lawii                                     Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy\n3     2 Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy Aglaia lawii (Wight) C.J.Saldanha ex Ramamoorthy\n4     3 Alangium uniloculare                             Alangium uniloculare (Griff.) King              \n5     4 Alangium uniloculare (Griff.) King               Alangium uniloculare (Griff.) King \n<\/code><\/pre>\n<p>This does what &#8211; I think you can do &#8211; if the <code>left_join()<\/code> approach and proper keys do not work. The drawback of this solution is that we &#8220;estimate&#8221; the full names.<\/p>\n<ul>\n<li>Thus, if the functions from <code>{stringdist}<\/code> do not help to get this right, you would need to specify your own &#8220;similarity&#8221; measurement.<\/li>\n<li>The result might be &#8211; mathematically &#8211; wrong as (dis)similarity results in equal distance for a certain combination of the wrong full name. You may need to break ties, etc.<\/li>\n<\/ul>\n<p>Hope this gets you going!<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">6<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Extract components of strings and fill-down where missing in R <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Based on the discussion in the comments it appears that it is not feasible to construct a key for joining the Species_name with a look-up table. What you could do is determine the &#8220;similarity&#8221; of your (species) names with such a look-up table. This assumes that your (species) names are different enough. To determine &#8230; <a title=\"[Solved] Extract components of strings and fill-down where missing in R\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\" aria-label=\"More on [Solved] Extract components of strings and fill-down where missing in R\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[321],"class_list":["post-4725","post","type-post","status-publish","format-standard","hentry","category-solved","tag-r"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Extract components of strings and fill-down where missing in R - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Extract components of strings and fill-down where missing in R - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Based on the discussion in the comments it appears that it is not feasible to construct a key for joining the Species_name with a look-up table. What you could do is determine the &#8220;similarity&#8221; of your (species) names with such a look-up table. This assumes that your (species) names are different enough. To determine ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-23T21:13:28+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Extract components of strings and fill-down where missing in R\",\"datePublished\":\"2022-08-23T21:13:28+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\"},\"wordCount\":507,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"r\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\",\"name\":\"[Solved] Extract components of strings and fill-down where missing in R - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-08-23T21:13:28+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Extract components of strings and fill-down where missing in R\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Extract components of strings and fill-down where missing in R - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Extract components of strings and fill-down where missing in R - JassWeb","og_description":"[ad_1] Based on the discussion in the comments it appears that it is not feasible to construct a key for joining the Species_name with a look-up table. What you could do is determine the &#8220;similarity&#8221; of your (species) names with such a look-up table. This assumes that your (species) names are different enough. To determine ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/","og_site_name":"JassWeb","article_published_time":"2022-08-23T21:13:28+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Extract components of strings and fill-down where missing in R","datePublished":"2022-08-23T21:13:28+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/"},"wordCount":507,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["r"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/","url":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/","name":"[Solved] Extract components of strings and fill-down where missing in R - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-23T21:13:28+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-extract-components-of-strings-and-fill-down-where-missing-in-r\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Extract components of strings and fill-down where missing in R"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/4725","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=4725"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/4725\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=4725"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=4725"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=4725"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}