"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["1558"],{6519:function(e,t,n){n.r(t),n.d(t,{default:()=>m,frontMatter:()=>a,metadata:()=>s,assets:()=>c,libParams:()=>h,params:()=>u,toc:()=>p,contentTitle:()=>d});var s=JSON.parse('{"id":"languages/r","title":"R","description":"LiveCodes runs R statistical programming language in the browser using WebR.","source":"@site/docs/languages/r.mdx","sourceDirName":"languages","slug":"/languages/r","permalink":"/docs/languages/r","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/r.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Python","permalink":"/docs/languages/python"},"next":{"title":"React Native (TSX)","permalink":"/docs/languages/react-native-tsx"}}'),r=n("5893"),i=n("65"),o=n("8500"),l=n("3365");let a={},d="R",c={},h={r:`library(dplyr)
starwars %>%
filter(species == "Droid")
`,languages:"r",console:"open",compiled:"none"},u={r:`head(iris)
PW <- iris$Petal.Width
PL <- iris$Petal.Length
species <- iris$Species
speciesID <- as.numeric(species)
plot(PL, PW,
pch = speciesID,
col = speciesID,
main = "Petal Width vs Length",
xlab = "Petal Length",
ylab = "Petal Width")
legend("topleft",
levels(species),
pch = 1:3,
col = 1:3)
`,html:`
Output
Plots
`,activeEditor:"script"},p=[{value:"Usage",id:"usage",level:2},{value:"Loading Packages",id:"loading-packages",level:3},{value:"Output Rendering",id:"output-rendering",level:3},{value:"Examples",id:"examples",level:3},{value:"Demo",id:"demo",level:2},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extension",id:"extension",level:3},{value:"Aliases",id:"aliases",level:3},{value:"Editor",id:"editor",level:3},{value:"Compiler",id:"compiler",level:2},{value:"Version",id:"version",level:3},{value:"Code Formatting",id:"code-formatting",level:2},{value:"Live Reload",id:"live-reload",level:2},{value:"Starter Template",id:"starter-template",level:2},{value:"Links",id:"links",level:2}];function g(e){let t={a:"a",blockquote:"blockquote",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"r",children:"R"})}),"\n","\n",(0,r.jsxs)(t.p,{children:["LiveCodes runs ",(0,r.jsx)(t.a,{href:"https://www.r-project.org/",children:"R"})," statistical programming language in the browser using ",(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/latest/",children:"WebR"}),"."]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsxs)(t.p,{children:["WebR is a version of the statistical language ",(0,r.jsx)(t.a,{href:"https://www.r-project.org/",children:"R"})," compiled for the browser and ",(0,r.jsx)(t.a,{href:"https://nodejs.org/en/",children:"Node.js"})," using ",(0,r.jsx)(t.a,{href:"https://webassembly.org/",children:"WebAssembly"}),", via ",(0,r.jsx)(t.a,{href:"https://emscripten.org/",children:"Emscripten"}),"."]}),"\n"]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsx)(t.p,{children:"WebR makes it possible to run R code in the browser without the need for an R server to execute the code: the R interpreter runs directly on the user\u2019s machine. Several R packages have also been ported for use with webR, and can be loaded in the usual way."}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://docs.r-wasm.org/webr/",children:"https://docs.r-wasm.org/webr/"})}),"\n"]}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsxs)(t.p,{children:["Check the ",(0,r.jsx)(t.a,{href:"#starter-template",children:"starter template"})," for an example."]}),"\n",(0,r.jsx)(t.h3,{id:"loading-packages",children:"Loading Packages"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"https://repo.r-wasm.org/",children:"Supported packages"})," can just be loaded in code, using the ",(0,r.jsx)(t.code,{children:"library()"})," function, without the need for any explicit installs. Packages are publicly hosted via a CDN in a CRAN-like repository with URL, ",(0,r.jsx)(t.a,{href:"https://repo.r-wasm.org/",children:"https://repo.r-wasm.org/"})]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n","\n",(0,r.jsx)(o.Z,{params:h,code:h.r,language:"r",formatCode:!1}),"\n",(0,r.jsx)(t.h3,{id:"output-rendering",children:"Output Rendering"}),"\n",(0,r.jsxs)(t.p,{children:["By default, the R code is evaluated and the output is rendered in the ",(0,r.jsx)(t.code,{children:"document.body"})," of the result page, followed by the plots (rendered as HTML canvas elements)."]}),"\n",(0,r.jsxs)(t.p,{children:["The evaluation and rendering behavior can be configured by adding a ",(0,r.jsx)(t.code,{children:"script"})," element in the HTML (markup editor) and setting ",(0,r.jsx)(t.code,{children:"livecodes.r.config"}),"."]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-html",metastring:'title="HTML"',children:"\n\n
`,f=`
`.trimStart();return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(l,{className:`container_Egsj ${e.className}`,style:{height:o||"50vh",...e.style},appUrl:a.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,s.jsx)(m,{js:u,ts:p,react:g,vue:v,svelte:f})]})}},8500:function(e,t,n){n.d(t,{Z:()=>d});var s=n("5893");n("7294");var r=n("6735");function i(e){let{children:t,fallback:n}=e;return(0,r.Z)()?(0,s.jsx)(s.Fragment,{children:t?.()}):n??null}var o=n("1705"),l=n("8294"),a=n("1858");function d(e){let{params:t,config:n,code:r,language:d="js",codeTitle:c="",showLineNumbers:h=!1,formatCode:u=!0,linkText:p="Run in LiveCodes",style:g={},className:m=""}=e,v=(0,l.r)({appUrl:a.G,params:t,config:n});return(0,s.jsxs)("div",{style:{marginBottom:"30px",...g},className:m,children:[r&&(0,s.jsx)(i,{children:()=>(0,s.jsx)(o.Z,{language:d,title:c,showLineNumbers:h,children:u?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}(r,d):r})}),(0,s.jsxs)("a",{href:v,target:"_blank",rel:"noreferrer",children:[p,(0,s.jsx)("svg",{width:"12",height:"12","aria-hidden":"true",viewBox:"0 0 24 24",className:"iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module",style:{marginLeft:"4px"},children:(0,s.jsx)("path",{fill:"currentColor",d:"M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"})})]})]})}},8294:function(e,t,n){n.d(t,{T:function(){return r},r:function(){return i}});var s=n(7728);async function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(t=e,e=null);let{config:n={},headless:s,loading:r="lazy",view:o}=t,l=s||"headless"===o,a=null,d=null;if("string"==typeof e)a=document.querySelector(e);else if(e instanceof HTMLElement)a=e;else if(!(l&&"object"==typeof e))throw Error("A valid container element is required.");if(!a){if(l)C(a=document.createElement("div")),document.body.appendChild(a);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(i(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",l?"eager":r);let u=globalThis.process;c.searchParams.set("sdkVersion",u?.env?.SDK_VERSION||"latest"),"object"==typeof n&&Object.keys(n).length>0&&c.searchParams.set("config","sdk");let p=t.params;"object"==typeof p&&Object.keys(p).length>0&&JSON.stringify(p).length<1800&&Object.keys(p).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(p[e])))});let g=!1,m="Cannot call API methods after calling `destroy()`.",v=await new Promise(e=>{if(!a)return;let t=a.dataset.height||a.style.height;if(t&&!l){let e=isNaN(Number(t))?t:t+"px";a.style.height=e}"false"===a.dataset.defaultStyles||l||(a.style.backgroundColor||="#fff",a.style.border||="1px solid black",a.style.borderRadius||="8px",a.style.boxSizing||="border-box",a.style.padding||="0",a.style.width||="100%",a.style.height||=a.style.height||"300px",a.style.minHeight="200px",a.style.flexGrow="1",a.style.overflow||="hidden",a.style.resize||="vertical");let s="livecodes",i=a.querySelector(`iframe.${s}`),o=i||document.createElement("iframe");o.classList.add(s),o.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),o.setAttribute("allowtransparency","true"),o.setAttribute("allowpaymentrequest","true"),o.setAttribute("allowfullscreen","true"),o.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),o.setAttribute("loading","eager"===r?"eager":"lazy"),l?C(o):(o.style.height="100%",o.style.minHeight="200px",o.style.width="100%",o.style.margin="0",o.style.border="0",o.style.borderRadius=a.style.borderRadius),addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),d=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!d||d<46)&&addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),o.contentWindow?.postMessage({type:"livecodes-config",payload:n},h))}),o.onload=()=>{e(o)},o.src=c.href,i||a.appendChild(o)}),f=new Promise(e=>{addEventListener("message",function t(n){n.source===v.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),f.settled=!0)})}),x=()=>g?Promise.reject(m):new Promise(async e=>{f.settled&&e(),v.contentWindow?.postMessage({type:"livecodes-load"},h),await f,e()}),j=(e,t)=>new Promise(async(n,s)=>{if(g)return s(m);await x();let r=L();addEventListener("message",function t(i){if(i.source===v.contentWindow&&i.origin===h&&i.data?.type==="livecodes-api-response"&&i.data?.id===r&&i.data.method===e){removeEventListener("message",t);let e=i.data.payload;e?.error?s(e.error):n(e)}}),v.contentWindow?.postMessage({method:e,id:r,args:t},h)}),y={},w=["load","ready","code","console","tests","destroy"],b=(e,t)=>{if(g)throw Error(m);return w.includes(e)?(j("watch",[e]),y[e]||(y[e]=[]),y[e]?.push(t),{remove:()=>{y[e]=y[e]?.filter(e=>e!==t),y[e]?.length===0&&j("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},S=e=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[e];addEventListener("message",async e=>{let t=S(e.data?.type??"");if(e.source!==v.contentWindow||e.origin!==h||!t||!y[t])return;let n=e.data?.payload;y[t]?.forEach(e=>{e(n)})});let R=()=>{Object.values(y).forEach(e=>{e.length=0}),v?.remove?.(),g=!0};function C(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===r&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await x(),t.unobserve(a))})},{rootMargin:"150px"}).observe(a);let L=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>x(),run:()=>j("run"),format:e=>j("format",[e]),getShareUrl:e=>j("getShareUrl",[e]),getConfig:e=>j("getConfig",[e]),setConfig:e=>j("setConfig",[e]),getCode:()=>j("getCode"),show:(e,t)=>j("show",[e,t]),runTests:()=>j("runTests"),onChange:e=>b("code",e),watch:b,exec:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),s=1;sf.settled?j("destroy").then(R):g?Promise.reject(m):(R(),Promise.resolve())}}function i(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:r={},config:i={},headless:o,import:l,lite:a,view:d,...c}=t;try{e=new URL(n)}catch{throw Error(`${n} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(t=>{let[n,s]=t;void 0!==s&&e.searchParams.set(n,String(s))});let u="headless"===t.view||o;if(a&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof i&&null==i.mode?i.mode="lite":e.searchParams.set("lite","true")),d&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof i&&null==i.view&&"headless"!==d?i.view=d:e.searchParams.set("view",d)),"string"==typeof i)try{new URL(i),e.searchParams.set("config",encodeURIComponent(i))}catch{throw Error('"config" is not a valid URL or configuration object.')}else i&&"object"==typeof i&&Object.keys(i).length>0&&(i.title&&"Untitled Project"!==i.title&&e.searchParams.set("title",i.title),i.description&&i.description.length>0&&e.searchParams.set("description",i.description),h.set("config","code/"+(0,s.compressToEncodedURIComponent)(JSON.stringify(i))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{h.set("params",(0,s.compressToEncodedURIComponent)(JSON.stringify(r)))}catch{Object.keys(r).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(r[t])))})}return l&&e.searchParams.set("x",encodeURIComponent(l)),u&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,n){n.d(t,{Z:function(){return l},a:function(){return o}});var s=n(7294);let r={},i=s.createContext(r);function o(e){let t=s.useContext(i);return s.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function l(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),s.createElement(i.Provider,{value:t},e.children)}}}]);