Inline R code in RMarkdown file showing "0" not correct result

I love R Markdown but have hit something I've never hit before. Two snippets of line code show the result 0 when they should show 93 and 40.4. If I run the code blocks above them and copy the code from the inline snippets into the console, I get the answers I expect. Here's a screenshot:

Here's what the Markdown comes out with:

"Ethnicity is a mess with 18 missing, 1 coded as “N/A” and 6 coded “NOT STATED”. There were 0 0 coded as “WHITE - BRITISH”, i.e. 0% 0 so I think there is fun to be had here but clearly ethnicity is going to need cleaning. I was assuming that those are the MDS stipulated categories but thinking about what I’m seeing I’m not so sure." The 18, 1 and 6 are correct but then the inline code is just giving zero not the correct answers. I've tried restarting Rstudio (after clearing the cache and files directories: same. I've tried moving the snippets: same. I've tried swapping single quotes for full quotation marks: same. As you see (if that screenshot worked), I've even tried pre-computing the values and using inline snippets that just call the values: same. Anyone seen this before? Any ideas?

You'll get faster answers if you post code, rather than screenshots: see A simplified data frame with contrived data and the same structure is all that's needed.

In the meantime, just on a hunch, put each snippet on a separate line, separated by blank lines, without the accompanied uncoded text. I can't see anything obviously wrong, but when I get this kind of problem, it helps me confirm that there's no syntax error, there is one, or some combination isn't playing well.

Some more things to try on the diagnostic front:

  • What happens if you put one of those calculations inside a code chunk? R Markdown renders in a separate session, so there can be cases where you can get one value interactively and another during rendering. It would be good to confirm whether those calculations only spit out zeroes inline, or if the inline thing is maybe a red herring.
  • What happens if you re-code the value in question (e.g., replace "WHITE - BRITISH" with "wb") and then run the inline code calculation?

And I'll second @technocrat's suggestion to try to make a stripped down sample .Rmd document that reproduces the problem. Either you'll succeed (and then people here will be better able to diagnose what might be happening), or along the way to doing so you'll find the answer yourself :grin:!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.