Questions
Browse questions with relevant R Language tags
6,312 questions
Has recommended answerCreate 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(...
How to change y axis individually in facet plots
Surprised that no one has offered ggh4x::facetted_pos_scales which personally is my first choice when it comes to setting the scales individually for each panel, i.e. instead of using patchwork or @...
Superimpose one ggplot on another
As partially suggested in a since-deleted answer, we can use patchwork::inset_element() for this. library(patchwork) Plot2 = ggplot(dat2) + geom_histogram(aes(x = x)) + theme_bw() + theme( ...
Using officer in R to hyperlink to a heading within Word documents
In general hyperlink_ftext would be the way to go. But after a look at the docs, the source code and some experimenting I think at present only external links are supported. However, with some ...
How to Scale ggplot2 Line Chart X-Axis (Time) to Reflect Proportional Time Differences in R
If we start with a simple frame of data, and try to plot it, dat <- data.frame(time=c("15m","45m","90m","3h","6h","9h","24h",&...
How to format the title of a facet_wrap plot to match the facet strips style?
Personally I would go for facet_grid but another, more laborious option would be to use ggtext::element_textbox: ToothGrowth |> ggplot(aes(x = dose, y = len)) + geom_boxplot(aes(fill = supp)) + ...
data.table two‐dot pronoun (..) in i or tidyverse bang bang !! equivalent in data.table
If you are locked into using data.table_1.14.8, I think a clear path is to use get(.) with a specific environment, as in library(data.table) packageVersion("data.table") # [1] ‘1.14.8’ reg &...
Two subtitles, one left-aligned, one right-aligned, on the same line
Hacky and spooky, but works. You can pass a vector to subtitle= and set the alignment for each element by passing a vector to hjust= (which of course is not officially supported): library(ggplot2) p &...
Concatenate cells into a text list for output in R
The issue is that you are using an inline code chunk with a function which returns a vector of length > 1. Instead you can use a code chunk with results="asis" and use cat as already ...
Label Encoding on multiple columns in R
Base R: cbind( DF, lapply(setNames(DF, paste0(names(DF), "_num")), function(z) as.numeric(factor(z))) ) # Gender School Town Gender_num School_num Town_num # 1 Male Primary HA ...
Changing alignment of a tick label in ggplot
Besides the option to add the label via an annotation another more recent option would be the legendry package which allows for stacked axes, i.e. in the code below I use compose_stack to add the ...
How can I add a risk table with cumulative events and number at risk using ggplot2
TBMK all out-of-the-box options which build on ggplot2 create the risk tables as a separate ggplot which is then combined with the chart of the survival curves using patchwork. But of course you can ...
Quarto PowerPoint slide with two plots side by side and descriptive text at the bottom of the slide?
The issue is that quarto or more precisely pandoc supports only a limited number of slide layouts (For an overview of the supported layouts see the docs), i.e. to display two charts side by side there ...
Create plot with variable height in facet_wrap
You can find the relevant code around line 660 of this file: https://dataverse.harvard.edu/file.xhtml?fileId=7522202&version=1.0 We can then manipulate that code for your data. However, there are ...
In ggplot2 how can I display in single legend the line color and point shape mapped to vector of single-character strings?
We can map the shape to cyl_word and force manual shapes: ggplot(mtcars2, aes(mpg, wt, color=cyl_word)) + geom_line() + geom_point(aes(shape=cyl_word), size=3) + scale_shape_manual(values = ...
Efficient method to estimate the group membership
If efficiency is at stakes, and the Interval is not necessarily contiguous, then we can write our own {Rcpp} function: library(Rcpp) library(inline) findIntervalGroup <- cxxfunction( signature(...
Change colour of text that labels a tile in ggplot2
I think your second code block ("Answer:") is a good approach, though you may run into problems when a fill is light enough that white lettering on the weekends will be washed out. An ...
Drop rows with missing values in all columns [duplicate]
I usually recommend collapse::na_omit for that. The oddly-specific prop argument will remove rows with a proportion of missing values >= prop. It's the fastest and most flexible option: collapse::...
Why does spec() return NULL after subsetting a tibble? (And how do I avoid that?)
The data for spec() is populated when the data is read-in or imported, and held in an attribute of the frame. Because of this, you won't see it on the console unless you look specifically for it: ...
Plot the best fit linear regression with the slope set to a fixed value (m=1)
library(ggplot2) library(dplyr) set.seed(3) ## adding a type column to showcase facets df %>% mutate(type = rnorm(n()) < 0, A = A + abs(rnorm(n())), B = B + abs(rnorm(n())))...
Irregular tick-lines when I add extra tick
You can explicitly set the positions for the minor breaks and grid lines using the minor_breaks= argument: library(ggplot2) ggplot(dat, aes(x, y)) + geom_point() + scale_x_continuous( limit = ...
How can I order y-axis (facet plot) by year correctly in ggplot2? [duplicate]
You are explicitly controlling the order of the y-axis with your call to factor(.) without controlling the order of the levels. Change that and it works. I need to fix some gaps in the data to get the ...
Expand existing table into a "versioned up-to-date statues" table [closed]
I'll Reduce over the unique iteration values, accumulating the results and combining at the end: library(dplyr) library(glue) Reduce( f = function(prev, iter) { full_join( filter(df_source,...
Manual change the color of the circles using sf package in R
Two options, plot all circles, with alpha and custom fill colours, overlaps will get different fill because of alpha. Or plot the 1st circle, then overlaps, manually setting the colours without alpha, ...
Legend not aligning under the graph using ggplot2
The issue is the setup of your shape (and color) palettes which prevent that the fill and shape legends get merged. In the code below I fix this by using named vectors of colors and shapes. ...
R reactome.db install failed
TL;DR -- go down to resolution. Troubleshooting In your case, when you try to install a package and there is an installation failure, there are a few things I normally check. Often there are OS-...
How to check if every data frame in the R environment has data
Here is solution using purrr: library(purrr) empty_dfs <- ls() %>% keep(~ is.data.frame(get(.x))) %>% keep(~ nrow(get(.x)) == 0) empty_dfs
Exclude column in sapply(dat_clean, FUN = function(x){x / sum(x)}) in R
Before calling rowSums, just select the numeric columns. Using @Friede's sample data, dat_clean <- data.frame(V1=letters[1:5], V2=1:5, V3=6:10) rowSums(dat_clean) # Error in rowSums(dat_clean) : 'x'...
column percentages with missings values on tbl_summary
Some alternatives: if you want to keep the "dichotomous" (yes/no, true/false) nature of the table where it only shows the "Yes" values, then it doesn't matter the number of "...
ggplot2 geom_textpath spiral with datetime axis
Internally, POSIXct is just numeric with a class: dput(Sys.time()) # structure(1745060382.54419, class = c("POSIXct", "POSIXt")) So while sin(Sys.time()) isn't going to work, we ...
How can I reorder and filter a range of time-formatted data in ggplot?
You can shift the times that are between 9 PM and midnight a day back, so they appear before and adjacent to the rest of your data with no gap. Note that in the example below, I don't have all of your ...
Comparing dates within a group but between variables (within a site but between record types)
Perhaps this? dplyr library(dplyr) dat |> arrange(date) |> mutate( .by = Site_ID, has_presence = cumany(grepl("presence", layer_type)) ) |> filter(has_presence, ...
Trying to download pdfs in R
An alternative approach for this URL: Open a web browser (I'm using FF, but others should work), open the dev-console (perhaps F-12 or some other method, browser-specific), and go to its "...
plotly_hover does not match data in shiny when using color aesthetic in the plot
Simply add a key to aes() which points to rownames(df). Then use that to subset and get df_select. server <- function(input, output, session) { df <- data.frame(x = 1:10, y =...
R-4.5.0 wininet not working to download packages
Up front, it appears that options(download.file.method="wininet") # in .Rprofile R> getOption("download.file.method") # inferred from comments # [1] "wininet" R>...
Simply submit a proposal, get it approved, and publish it.
See how the process works