R Language Collective

A collective where data scientists and AI researchers gather to find, share, and learn about R and other subtags like knitr and dplyr.
A collective where data scientists and AI researchers gather to find, share, and learn about R and other subtags like knitr and dplyr.

Pinned Bulletins

View all 1 bulletins

R Language has some news to share

Bulletin
1 min read
1k views

Welcome to the R Language Collective

Questions

Browse questions with relevant R Language tags

491,119 questions

0 votes
1 answer
14 views

How to join by everything except specified columns in dplyr?

I have two datasets that share all columns and I would like to make an anti-join based on all of the columns except two of them. For example, I would like to do something like the following: library(...
0 votes
1 answer
29 views

How to get the actual seed which we set using set.seed() in R?

I want to get the seed back which I set using set.seed(). Say if I set seed as set.seed(123), I want to get 123 back if I called some sort of function like 'get_seed()'. I want to make sure that if ...
0 votes
1 answer
17 views

How to efficiently get maximum value and its origin in R data.table?

does anyone know a more efficient, and dynamic, way of assigning the maximum value and its origin to columns in a data.table. An mtcars example is shown below library(data.table) DT <- data.table(...
0 votes
0 answers
7 views

Update Quarto in RStudio

I would like to update Quarto inside the terminal of Rstudio to v1.3.290. I followed the installation like described here, but I keep getting errors which I am not sure about. I runned the following ...
  • 30.7k
1 vote
0 answers
11 views

Use `trace` to skip a line in an R function

Assume I have a function where I want to tweak the behavior a little bit (skip a certain line, say). I could Copy & paste the function and change it. Use debug to change the code interactively. ...
  • 15.7k
0 votes
1 answer
11 views

Anonymous function in summarise() with pick(everything()) gives: error in pick() Can't subset columns past the end

I'm trying to understand how to use anonymous functions with summarise. For the sake of providing a simple MRE, if I do: tribble( ~A, ~N, "a", 1, "a", 2, "a"...
  • 1,427
0 votes
0 answers
7 views

Is there any way to enqueue db operations?

My problem is that my RScript takes too long to insert data into the DB, so if the operations could be queued in a private queue it could increase the execution speed. I need to be able to use ...
  • 19
1 vote
2 answers
25 views

Add custom tick on and a label y-axis with custom colour using ggboxplot()

I have a boxplot that I've created using ggboxplot. On it I have a horizontal line at the mark y=50. I want to be able to add a label at y=50, x=0 saying "50" in dark green to match the line....
0 votes
1 answer
24 views

Remove exactly one word bafore another word R and the word

I need to remove exactly one word before a given word in R. The string is: string <- c('first local hospital orlando', 'state hospital claifornia', 'state hospital orlando') I know how to delete ...
0 votes
1 answer
39 views

Extract the three words following the keywords [closed]

This regex written in R code extracts both the keywords and the words following them: regex <- paste0("(?i)\\b", keywords, "\\b\\s+(\\w+\\s+){0,2}(?!\\b", keywords, "\\b)\\...
  • 11
0 votes
2 answers
30 views

merge elements of the list that have same name by column if the element length is the same

I have data that looks like this: a<-rnorm(10, 1,1) b<-letters[1:10] ab<-cbind.data.frame(a,b) ab a<-rnorm(10, 1,1) b<-letters[1:10] cd<-cbind.data.frame(a,b) list1<-list(ab,...
  • 136
1 vote
0 answers
6 views

How can I create a raster from my data in order to extract data using a shapefile in R?

I have a netcdf file that I read into R, perform some analysis and ultimately produce data in the list format below: vap=array(1:100, c(1,451,351)) #create the list Variable <- list(Data = vap) ...
  • 162
0 votes
0 answers
8 views

lmer(): Error in is.nloptr(ret): objective in x0 returns NA

I tried to build a linear mixed model using the function lmer(), then I get the following error: MOD_1 <- lmer(Variable~fixed_effect*random_effect + (1|random_effect), data = My_data) Error in is....
0 votes
0 answers
16 views

change font familly in geom_text_repel()

Summary I would like to use AvantGarde font family in a geom_text_repel but I get an error. Minimal code example library(ggrepel) p <- ggplot(mtcars, aes(wt, mpg, label = rownames(...
2 votes
3 answers
41 views

Extract text between matching parentheses

Consider the following example: x <- "something('pineapple', 'orange', y = c('peach', 'banana'), z = 'lemon'), something(v = c('apple', 'pear'), z = c('cherry', 'strawberry', 'grape'))" ...
  • 837
1 vote
1 answer
21 views

Loop to create multiple subsets and dataframes [duplicate]

I am using R and I have the following data frame: data <- data.frame(ID_CODE = c('001', '001', '001', '002', '002', '003'), Metric1 = c('0.94', '0.68', '0.8', '0.12', '0.56', '0.87')) I would ...
0 votes
0 answers
19 views

I try to run a function from a sourced R script in R but I get the error that it doesn't exist

I get this error when I run the function. Error in function1(paramter) : could not find function "function1" The function is in a sourced R script which shows no error when sourced and also ...
  • 21
0 votes
1 answer
18 views

geom_bracket (ggpubr): italic p value with asterisk in expression

I've searched the entire internet for a solution, but none of the posts seemed to cover my exact problem. Sorry if I missed the answer somewhere. I'm trying to create to add a bracket with a p-value ...
0 votes
0 answers
8 views

Fusing data from multiple data frames with certain conditions

I have 2 dataframes. 'df1' contains, among others, an overview of 1000 genes used in an experiment but only by their 'GENE_*ID'. 'df2' is a repository with 4020 'GENE_ID's with their names ('SYMBOL') ...
  • 1
1 vote
3 answers
22 views

Reverse ordering in of legend in ggplot

library(tidyverse) n <- 100 df <- data.frame(grp = sample(c("A", "B", "C", "Total"), size = n, replace = TRUE), value = runif(n = n, min ...
  • 1,535
0 votes
2 answers
32 views

selecting the highest variable in a column per identifier

I am having a little difficulty with something which I am sure better R users will find very easy. I have a dataframe arranged by identifiers on each row, however some have two rows per identifier. ...
  • 91
0 votes
0 answers
19 views

How to filter rows in a sf objects with a sample point

I want to library(sf) library(sp) data(meuse) meuse_sf <- st_as_sf(meuse, coords = c("x", "y"), crs = 28992) # I want to extract one point geometry such as meuse_sf[1,], and ...
  • 51
0 votes
0 answers
10 views

How to calculate the SPI and SPEI at each grid-level

I wanted to calculate the SPI and SPEI at grid-level using R software at timescale of 3 months. library(SPEI) spigrid<-read.csv("GriddedMonthlyRF.csv") I tried the following two ...
  • 1
-1 votes
0 answers
27 views

Advance Loop in R

See the following table: Now I want this code to execute for all these 4 factors: export(list(Table = Data1$BaseRate), "IEL_HS_CA_BASE_RATE.xlsx"); #Export only one table at a time for ....
0 votes
0 answers
11 views

R, convert R object to netcdf

I am trying to conver the following R object to netcdf file: test.rds The file contains a gridded atmospheric variable over the entire globe for 12 time steps. Here below is the code I am using: ...
  • 105
1 vote
0 answers
19 views

Install package on R 4.2.2 (with Ubuntu 20.04)

I am trying to install arrow package on my Ubuntu 20.04 server with R 4.2.2 by the instruction introduced here : options( HTTPUserAgent = sprintf( "R/%s R (%s)", ...
  • 1,935
0 votes
0 answers
11 views

Two questions (P-value and interpretation of the coefficients) when using ordinalNet function fitting elastic-net penalized ordinal logistic model

I want to fit a regression model using variables concerning the Diabetes status. The reponse variable have three degrees which are normal fasting glucose, impaired fasting glucose and diabetes. Here ...
0 votes
0 answers
29 views

Getting seed always returns NULL in R [closed]

I have found following solution in many links. But I am always getting NULL. set.seed(123) randomNum <- runif(1, 0, 1) seed <- attr(.Random.seed, "seed") print(seed) Initially I ran ...
0 votes
0 answers
15 views

Bootstrapping emmeans derived from a multilevel regression, but "Error in t.star[r, ] <- res[[r]] : number of items to replace is not..."

I have a dataset in which participants went through 5 different situations and their behavior was measured in each situation. Here's an example dataset with a similar structure: id1<-1:10 id<-...
  • 103
1 vote
1 answer
27 views

Integrating the PDF of a t-distribution in R via integrate()

I am trying to replicate the t-test with mathematical formulas and it somehow wont work with may current attempt below: # PDF t-distribution: t_distr = function(x,df){ t_1 = gamma((df+1)/2)/(sqrt(df*...
3 votes
0 answers
51 views

Reassigning value in 3d array in R is very slow

I'm trying to re-assign values by index in a (fairly) large array in R. However, it seems wildly slow. Is there a faster way to run this? For example, for me re-assigning just one value in my array ...
  • 113
0 votes
1 answer
13 views

'Import dataset' function in Rstudio stopped working

When I click on 'Import dataset' function in the upper right corner of Rstudio, I get this: I use this function and that particular dataset every day, and such an error never showed up before. Simple ...
  • 41
2 votes
2 answers
38 views

Using `optimize` to solve for X in an equation in R

Below, I wonder how to find the value of x which I expect to be about .2? f = function(x, y = 0.07925971) pnorm(x) - pnorm(0) == y # Tried: optimize(f, c(-4,4)) # Tried: uniroot(f, interval = c(-4,4)...
0 votes
0 answers
18 views

How can show all legend labels on a bar plot, without dropping them when data does not exist? [duplicate]

I am using patient dataset to determine which medications (amiodarone & digoxin) they are taking. Here is the classifer I am using topcat$aARGroup <- with(topcat, ifelse((is.na(amiodarone) &...
0 votes
1 answer
28 views

How to refer existing columns in data.table's set()?

I need to create a new column in my data.table based on existing column. Of course it is easy to do with [ notation (like iris[, newcol:=toupper(Species)]) but I wanted to use %>% piping. This code ...
  • 8,144
0 votes
0 answers
27 views

R Return Only Non-Zero Values

Suppose I've defined vectors A-E of different lengths. E has length of 2. Here's the code E<<-c("name1", "name2") t_array<<- array(NA, dim= c(A= length(A), ...
0 votes
1 answer
36 views

Add a row to data frame containing numeric and non-numeric data

I have a series of data frames that I need to add a row for totals to before I print them out using kable. The frames contain numeric and non-numeric data. Maybe it's just a case of Sunday slow brain, ...
  • 39
0 votes
0 answers
18 views

R: Creating a Matrix to Store Join Results

I have these two shapefiles in R: file_1:https://www12.statcan.gc.ca/census-recensement/alternative_alternatif.cfm?l=eng&dispext=zip&teng=lada000b21a_e.zip&k=%20%20%20151162&loc=//...
  • 5,173
2 votes
1 answer
34 views

Category order in bidirectional bar plot

I am trying to generate a simple bar plot of categories mapped to positive and negative values. I understand that category order is set via factor in ggplot2 however, the categories are only in order ...
0 votes
0 answers
7 views

Running LightGBM algorithm after the implementation of SMOTE function to mitigate the issue of managing imbalanced dataset

I need to run a lightGBM model with an imbalanced dataset. The dataset has a 'Target' variable with a binary result, "0" with 61471 registers and "1" with 4456 registers. To ...
1 vote
1 answer
36 views

How to properly implement the Modified Gram-Schmidt Algorithm in R Code? [duplicate]

For context, this is the algorithm I am trying to replicate in R: This is the code I have implemented. X = matrix(c(1, 2, 0, 3, -1, 4), nrow = 3, ncol = 2, byrow = T) txtMGS <- function(A){ Q &...
0 votes
0 answers
14 views

How to loop through a function comparing successive years within an ID when number of years differs for each ID

I have a function to calculate the overlap between two home ranges: gOverlap <- function(hr1, hr2) { a <- gIntersection(hr1, hr2) if (is.null(a)) { return(0) } gArea(a, byid=TRUE) / ...
-1 votes
0 answers
15 views

R code to produce an output of number of days as 2247.3333 between 2009-11-06 and 2016-01-01

start_date = as.Date(2009-11-06) end_date = as.Date(2016-01-01) R code for number of days as 2247.3333 library(tidyverse) difftime(start_date, end_date, units = "days") output: 2247 expected ...
  • 1
-1 votes
0 answers
30 views

When i try to run R in VScode doesn´t work

I am having some problems running R in VScode. I try installing "radian" using different documents that I found online, but always I end up with the same error "couldn´t find radian&...
0 votes
0 answers
32 views

How to make calibration plots from predictions of binary outcome?

I have made several models (RF, XGB and GLM) to predict a binary outcome and they all achieved an AUC of approximately 0.8 and a brier score of 0.1-0.15. I am trying to create calibration plots and I ...
  • 15
1 vote
1 answer
17 views

is it possible to define a list of reactive values with a formula?

I am making a shiny app as a hobby which is a model with variables that change over time depending on both inputs and other calculated fields. I've done this using a sliderinput and observeevent for ...
  • 11
0 votes
1 answer
36 views

R: summarise by ID only when the same ID repeat twice but don't summarise if it repeats more then twice

I'm trying to summarise a dataframe by ID but I would like to summarise only when the same ID repeats in two rows and not summarise when the same ID repeats in more than two rows. I have tried: df %&...
0 votes
0 answers
16 views

Are the coefficients in `lme4` correct with nested effects? [migrated]

The coefficients I'm seeing from a merMod model produced by lmer are not what I'd expect. I made a reproducible example to illustrate. I assumed that the Days coefficient reported for a nested effect ...
  • 1,079
0 votes
1 answer
14 views

Latex with katex rendered double in R Shiny app and as unwanted popup in new window

My R Shiny application uses Katex to render the latex - this is my header in my navbarPage() in my ui: header = tags$head( # use Katex to autorender all tex: https://katex.org/docs/...
0 votes
1 answer
32 views

Ordering inside of pipeline

Is there is some way to include the ordering part inside of the pipe without having to make 2 separate variables. # Find average tooth length by suppliment, by dose, rounded to 1 decimal point # ...


1
2 3 4 5
9823