Questions
Browse questions with relevant R Language tags
6,348 questions
Has recommended answerHow to format numbers with commas using table1
library(table1) set.seed(42) dat <- data.frame( Group = factor(rep(c("Treatment", "Control"), each = 50000)), Count = round(rnorm(100000, 50, 15)), Category = ...
How to correctly read German special characters from CSV file in R on Linux?
Looking at the file, it is incorrectly encoded. It does satisfy the requirements for looking like a UTF-8 file, but it doesn't encode the characters you are expecting. For example, in Nürnberg, the &...
Persist R function defined in Rprofile even if user clears environment
Edit: changed from using rlang::env_unlock() (which is deprecated) to something more local. Somes notes about this: I'm using dot-names, mostly because it is one-step more to "find" them ...
Creating (ggplot2-)boxplots based on integer x values with correct spacing on the x axis
A pure {ggplot2} option would be to convert your p column to integers and to explicitly set the group aes to group by both p and q: library(ggplot2) set.seed(123) min_ex <- data.frame( p = ...
Plotting actual words as the bars in R
Yet another ggplot option, if you want your labels to sit inside actual bars: library(tidyverse) df %>% mutate(nchar = nchar(Title)) %>% ggplot(aes(Year, 0)) + geom_label(aes(label = ...
Select and deselect an entire group of choices on a pickerInput from shinyWidgets
In the original solution in the other thread, event listeners "piled up" with no clean-up, which was breaking the functionality. Here, I am using .off() to remove duplicate event handlers ...
issue in MLE of New Generalized Poisson lindley Distribution
The problem is for your pmf to be valid, alpha and beta need to be constrained. As I understand it from the original paper, alpha needs to be > 1 and beta needs to be > 0. If these constraints ...
Usage of options(warn=2) and tryCatch() with purrr R library
Up front: This is an "inadvertent feature" of future, and may not be avoidable without some (not insignificant) code-inspection and inference. (I also think it has nothing to do with furrr ...
Plotly Returning a Blank Plot? [closed]
The issue is the setup of your data, i.e. your data is organized as a data.frame whereas a Plotly surface plot requires a matrix. Hence, to fix your issue you should convert your data to a matrix: ...
In ggplot2 facet grid with distinct start x-axis scale
The use of patchwork in @GregorThomas's answer is my usual first-attempt, and it works well. Another method is to use ggh4x::facetted_pos_scales to define the x-axis individually for each facet: ...
How can I change the color of censor points on a ggsurvplot?
Here's another method by drawing the points after creating the ggsurvplot: library(survival) library(survminer) ggsurvplot( survfit(Surv(time, status) ~ sex, data = lung), data = lung, censor....
how contain setCalendar() in qlcal to the scope of a function?
The package doesn't seem to support that scenario, but you can use the base R on.exit() to reset values when your function exits. You can use isHolidayInCal <- function(date, calendar){ ...
Corrplot top labels distance
You could add a break to each name of the matrix to add some space like this: data("mtcars") library(corrplot) library(RColorBrewer) car_matrix <- cor(mtcars, use = "pairwise....
How to access data in json downloaded via API
When you look at the basic structure, str(resp_body_json(resp)) # List of 1 # $ USA:List of 62 # ..$ :List of 7 # .. ..$ AssetCount: int 0 # .. ..$ Emissions : int 0 # .. ..$ Year : NULL ...
How to plot iterating over rows in R
As you mention iterate row by row, we can plot every row one at a time with gganimate: library(gganimate) X$rn <- seq(nrow(X)) p <- ggplot(X, aes(x = 0, xend = 1, y = T0, yend = T3, colour = ...
Multiple Regression Especification in one Plots [closed]
This looks like a customized type of upset plot. Without knowing your starting point, it's very difficult to give concrete advice. However, we may show an example of how you could go about creating ...
How to program a dispersion graph? [closed]
If I understand you correctly, you have a variable called sdq which is presumably a numeric score between 0 and 25. You also have a variable called adhd which is a character vector of "yes" ...
Generating a flexdashboard with plotly plots in a for loop but unable to get desired result when accessing elements in a list of tagLists in a loop
As you did not provide a working or runnable example one can only guess what's the issue with your code. Below is a minimal working example base on the mtcars dataset which uses a nested for loop to ...
What is the R equivalent to Python's ZipFile.writestr
I am not aware of an exact equivalent of ZipFile(..., 'a'). There is zip::zip_append, but you need to write your mytext to a file (temporarily) before appending it. library(zip) mytext <- "...
Use R to visualize activities across 24 hours as a pi chart 'clock' or bar
I suppose it's just for fun, but why not show a whole week's worth using a spiral track? Create a little helper function and a data frame of the week: posix_to_mins <- function(x) difftime(x, as....
Customizing legend when plotting plotting geom_spatraster and geom_spatvector in R
To get a separate legend map on the shape aesthetic instead of setting the shape as a parameter and use e.g. scale_shape_identity. Additionally I explicitly set the order of the legends via ...
Order bars within stacked barchart by value in plotly R
We could use geom_rect to imitate stacked bar chart. Adapt colours, xaxis labels as needed, and convert to plotly. data <- data %>% ungroup() %>% mutate(xmin = as.numeric(as.factor(...
How to get the same results using`rpois` and `rpoispp` from spatstat [closed]
The docs for rpoispp specifically say: warning Note that lambda is the intensity, that is, the expected number of points per unit area. The total number of points in the simulated pattern will be ...
Set operations with selection helpers
If I undestand your question correctly, you can achieve your desired using all_dichotomous() & !"PAIN_SCALE", i.e. instead of a set operation we have to use a boolean operation in a tidy ...
geom_text - concatenate stat and variable in the label [duplicate]
When you apply a stat the original data gets transformed and the original columns and column names are no longer available or present in the transformed data. But as you map trans on the fill aes the ...
How to properly combine two ggplots and properly align axis and strips/titles?
patchwork's free() lets you remove the alignment, so you could do (free( p1 + ylim(0, 6) ) | free( p2 + ylim(0, 6) + theme_bw() )) & theme( plot.title = element_text( hjust = ...
Move Facet label to the left to make space for legend [duplicate]
As started by @Edward's comment, use axis.title.* theme arguments. ggplot(mtcars, aes(mpg, disp)) + facet_wrap(cyl ~ ., ncol = 2) + geom_point(aes(color = factor(gear))) + scale_y_continuous(sec....
How to extract tables hierarchically (grouping by title) on a website using rvest?
The logic and code to scrape every webpage is going to be somewhat different and there's no guarantee the HTML structure won't change in the future. In order to scrape a page, you're going to have to ...
How do I parse text from my front-end into R?
#* @post /api/generate-graph function(req, res) { # uploaded file and fields file_info <- req$files$file graphType <- req$body$graphType xAxis <- req$body$xAxis yAxis <- req$...
How can I calculate the number of local maxima in a 3D matrix in R?
The question implies data is in the format of a 3D mesh, like molaR::Hills. It seems to me that the simplest way forward is to convert the mesh into a 2D raster. We can do this by using the vertex co-...
Adjust axis label placement on ggcorrplot
You can turn off the y axis labels and add a geom_text layer containing calculated label positions from your correlation matrix. It also requires turning clipping off: library(tidyverse) library(...
Warning messages with plotting density lines on top of histrogram in R
The reason you are getting the warnings is that you are specifying the data and mapping arguments in the initial ggplot() call, which means each layer inherits your data frame and mapping. Since ...
Adding horizontal line the fill part of the width for categorical x-axis
You can avoid the need for explicit user-space calculations by using the I() notation to represent npc co-ordinates since ggplot v3.5.0. To get a line spanning the middle 70% we just need x = I(c(0.15,...
Adding normal density plot to histogram in ggplot - A follow up question [closed]
Up front, the error and warnings: Error in geom_line(aes(x = dat[dat$met == "Metric2", ]$val %>% { : Problem while computing aesthetics. ℹ Error occurred in the 4th layer. Caused by ...
Create a string from data in a dataframe column in R
The documentation might be a little misleading. It says Usage: validator(..., .file, .data) Arguments: ...: A comma-separated list of validating expressions .file: (optional) A ...
Why does `tapply` give a different result depending on the parameter of FUN
When FUN= returns a scalar for all calls, then the default of simplify=TRUE means that it is turned into a vector, non-indexed positions are assigned NA as an indicator of missingness, and this vector ...
How can I set "cr" as the default basis type in mgcv::gam instead of "tp"?
The function s is defined with bs = "tp" as a default argument. There aren't any settings anywhere that can change this. Furthermore, you can't even define a wrapper of s because of how gam ...
How to functionalize base R function like `with()`?
You are on the right track with rlang::inject(). But note that the documentation states that You can use {{ arg }} with functions documented to support quosures. Otherwise, use !!enexpr(arg). So let’...
re-order factors on y axis of a gantt chart
The y axis is in alphabetical order, but factor ordering is such that earlier letters in the alphabet get the lowest values, so when these are plotted they are lower on the y axis. Therefore the order ...
How to write multiple named sheets to excel workbook using openxlsx
You said you needed to use openxlsx because of issues with java, have you tried writexl? Perhaps something like this: strsplit(file_list, "_") |> sapply(function(st) paste(st[1:4], ...
Adding custom HTML before <div class="main-container">
I think we can fix this with a little more css: body { background: url(https://linesteppers.com/tutorials/RMarkdown/img/BannerImage_TreeBlossoms_4470x3024.jpg); /* remove margin and padding */ ...
Color edge links in ggraph based on specific nodes
The original data passed to ggraph gets transformed by geom_edge_link, i.e. by default get_edges() is called to extract the edges data from the graph object or the data frame in your case. As a result ...
Facet wrap in R for gglikert plot
The issue are the missings in the transformed data created by gglikert (most likely due to the wide format of the input data), i.e. even if there are no answers or responses the questions are not ...
Concatenate values depending on variable value [closed]
Assuming that df1's row 4 should really be retained in the results, here's a dplyr pipe: library(dplyr) df1 |> mutate(.by = c(taxonID, locationID), g = (establishmentMeans %in% c("introduced&...
More efficient way to compare if a DateTime is in between any of two columns of DateTimes in R? [duplicate]
data.table::inrange library(data.table) as.data.table(hr_clean) |> _[, is_sleeping := inrange(dateTime, sleep_ranges$startTime, sleep_ranges$endTime)] # dateTime is_sleeping # ...
X-axis scale over night
Recognizing that your use of geom_bar is just a placeholder for real data and other plot needs, I think your main concern is how to adjust time and the x-axis so that it does just what you want. For ...
iteratively decrease values in observations for a grouped dataset without changing observations in the first rows using group_map and return a tibble
Up Front: I should note that assuming perfect equality for grouping by value will be subject to floating-point issues as discussed in Why are these numbers not equal?, Is floating-point math broken?, ...
Only update value when pushbar closes
We can detect the pushbar's state, save the switch value to a temporary variable, and only write it to the value that will be rendered upon closing the pushbar. I checked the class of pushbar, and it ...
How to use a dominant fill color in geom_col_pattern when 2 colors are used?
Since R v4.1.0, you don't need to use ggpattern to create a gradient fill in ggplot2. You can do it directly by passing a grid::linearGradient as the fill colour of the bars. Furthermore, it gives a ...
How to position the north arrow using tmap r package?
We can use tm_pos_in(..) to get closer: tm_shape(r, bbox = bbox_new) + tm_raster(col.scale = tm_scale_continuous( values = "viridis"), # color palette; col.legend = tm_legend(...
Simply submit a proposal, get it approved, and publish it.
See how the process works