Questions tagged [dplyr]
Use this tag for questions relating to functions from the dplyr package, such as group_by, summarize, filter, and select.
36,452
questions
0
votes
0
answers
12
views
Output of weighted percentile distributions with multiple groups
I am relatively new to R after years of SAS coding. I am trying to output many different weighted percentiles on multiple groups. I am trying the following code -- please note that "VarName&...
3
votes
3
answers
69
views
Is there a way to replace a group of strings with another group if strings via dplyr and stringr
I have reproduced a simple version of my problem. I essentially want to replace the English words in the statement column with the Spanish equivalent, for all statements.
library(tidyverse)
english &...
1
vote
4
answers
82
views
Convert List Column to String of Comma-Separated Values
I have the following data.frame. How can I convert the color_names column to a comma-separated string? A dplyr solution is preferable.
tibble::tibble(
col_hex = c("#0087BF", "#...
0
votes
2
answers
68
views
Vary basic question about the native pipe and tidyverse
I can't figure out what works and what doesn't with the native pipe. Here are 2 examples, that I expect to work, but fail. I guess my problem is that I though it would work like the magrittr pipe.
Is ...
0
votes
1
answer
36
views
r generate indicator columns based on conditions
Suppose this is my dataset
State Enter Event Lag
State-A 2000 2004 -4
State-A 2001 2004 -3
State-A 2002 2004 -2
State-A 2003 2004 -1
State-A 2004 2004 0
State-A 2005 ...
0
votes
1
answer
50
views
How to merge rows
I'm new to coding with R, and need to find a way to edit my data frame for a stacked bar plot using R. I need one column with character values, followed by two columns with numeric values. This is the ...
1
vote
3
answers
68
views
Determine and list the top 5 for a given group
I need to determine the top 5 defects (determined by distinct count of event_id) for each company and list them as shown in df_answer.
df= data.frame(company=c("X","X","X"...
2
votes
3
answers
72
views
How can we mutate an new column name containing an existing value
The median of mpg is 19.2.
In the next line I would like to add this info (e.g. "19.2") to the new mutated column name "median_dich". So that at the end the new column name should ...
1
vote
1
answer
47
views
How to replace with NAN no more than 30% of the values with the specified flag in R
I have such dataset (example)
dat=structure(list(Y = c(2282L, 2565L, 2242L, 2109L, 2704L, 2352L,
2492L), is_red_ndvi_v_down = c("yes", "yes", "no", "yes", &...
2
votes
3
answers
60
views
How to convert a list of vectors of unequal length to a binary data frame?
How to convert a list of vectors of unequal length to a binary data frame? My dataset looks like:
> gene_annot
[[1]]
[1] "lipid binding" "catalytic activity" &...
0
votes
1
answer
41
views
Identifying crisis episodes
New R user here.
I have a relatively large panel of countries, and I want to identify recession episodes.
labor_pivoted_crisis=labor_pivoted%>%
group_by(country)%>%
mutate(crisis=ifelse(...
1
vote
1
answer
66
views
Separate 1 column into 2 based on occurrences on the same day in R?
I'm trying to do a social network analysis and create a data frame of associations. I have 2 columns, one with ID and one with Date. I want to separate the ID column into a "from" and "...
0
votes
0
answers
24
views
Stratified Sampling in R with a slightly unbalanced sample?
I am trying to pull out a subset of some data so I can try out reliability coding for a research project. I am having some trouble pulling out a stratified sample from this data set.
Here is the code ...
2
votes
5
answers
117
views
Decoding multiple hot-encoded columns efficiently in R
I have the following data frame:
id = c(1,2,3)
where_home = c(1, 0, NA)
where_work = c(0, 1, NA)
with_alone = c(0,0,0)
with_parents = c(0,1,1)
with_colleagues = c(1,1,0)
gender_male = c(1,0,1)
...
0
votes
2
answers
44
views
Using group_by and count in user defined functions
I have created function using the group_by and count but I don't get the results desired...
count_func <- function(groupvar, outcome){
mtcars %>%
group_by({{groupvar}}) %>%
count({...
1
vote
3
answers
52
views
How can I convert the format of my dataframe into a new transposed format in R?
I would like to convert my dataframe, df1, to the format shown in df2. How can I do this in an efficient manner without hard-coding & while using R libraries?
df1 <- data.frame(
A = c(1, 5, 3,...
5
votes
3
answers
98
views
Return values from multiple columns to a new column where the last character in column names == last character of values in reference column
I'm needing a more flexible method to extract values from multiple columns into column "y" where the last character in "x" == the last character of the column name. I can achieve ...
3
votes
1
answer
101
views
how divide series of columns to one column
I have a DataSET with more than 5e5 individuals as follows:
library(tidyverse)
sample <- tibble(
iD=c(1,2),
age=c(38,40), born_1=c(14,1),born_2=c(9,NA), born_3=c(4,NA), born_4=c(0,NA), asfr15=...
0
votes
1
answer
40
views
Transforming Nested Lists in R for YAML config
I have a config file for Mkdocs in Yaml that I'm trying to modify, and it requires a slightly strange nested list structure. After finding some code online that turned a dataframe into a standard ...
0
votes
2
answers
41
views
R: calculate the unique count of observations that meet conditions across two different columns of a data frame
I have an example dataset that contains the details of a survey. The id is repeated for number of members in the famiy. I aim to get the total count of households, identify the sum of households with ...
1
vote
1
answer
43
views
Transpose dataframe in R and maintain first column
I need to transpose a dataframe in R, making the first column the headers of the transposed df, and the current columns headers the values in column 1 of the df. Like this -
df =
| |S1|S2|S3|
1|A|1 ...
0
votes
1
answer
23
views
Using mutate() and mean() to get the average of columns whose names are stored in a vector?
I'm trying to write a simple function that I can re-use whenever I'm creating a composite score of several items.
Here's a simplified version of what I'm trying to do:
item_names = c("item1",...
0
votes
0
answers
20
views
I want to load filtered table from RSQlite data base into R
I have two tables (table1 and table2) in my RSQLite database. table1 is big (20GB) so I want to filter it with dplyr and then I use collect() to load it into R work space. table2 has (626 397 ...
1
vote
4
answers
110
views
Group by variables to create new column in R
The first table is the data at hand and I am looking to create table-2 using it. In the second table, value is the important variable that needs to be created. It is created using first table. We ...
2
votes
2
answers
58
views
Rolling mean across day of year
In my example below, I can calculate a centered 7-day rolling mean however, the first three days and the last three days are NA values. The rolling mean should take into account that day 365 is ...
0
votes
1
answer
73
views
Creating side by side table for longitudinal analysis in R
I have a merged dataset that includes two longitudinal studies having recorded measurements from study1 and study2. I can provide an example as below -
data <- data.frame(
weight_study1 = rnorm(...
0
votes
0
answers
27
views
Investr package strange behaviour with dplyr mutate
I'm working on a script for calibration curve comparison (analytical chemistry).
To simplify: I have independent variable exp_conc (concentration of calibration solutions used to calibrate)
and ...
0
votes
1
answer
30
views
Determine start and end dates for multiple events and groups
I have a dataframe of three columns site, Date, and Event. There are two sites, a series of dates, and a factor denoting if an event occurred or not (no event is coded as 0, events are coded as 1). I ...
0
votes
2
answers
39
views
How to use mutate_at over multiple columns specified as function argument
I am trying to overwrite multiple columns specified in the function argument based on condition in case_when. However, columns are not being updated. Any advice on what is not working in this code?
...
1
vote
2
answers
48
views
Applying case_when to dataframe based on list of functions in another dataframe
I am trying to apply case_when to selected columns in dataframe_1 based on a list of case_when functions in another dataframe.
For example, using the mtcars dataframe:
mpg
cyl
21
6
21
6
22.8
4
I ...
1
vote
1
answer
36
views
Renaming multiple columns using a column index
Here is my example data.frame
df <- tibble(
ID = 1:3,
col_x = LETTERS[1:3],
col_q = letters[1:3],
col_w = 3:1
)
> df
# A tibble: 3 × 4
ID col_x col_q col_w
<int> &...
0
votes
2
answers
33
views
How can I pull rows that match an exact string of characters, but that is buried within a larger string?
I need to filter out rows in a data frame that contain this exact string "S[Phospho(STY)]Q". However, in every case this string is in the middle of a larger string, never at the beginning ...
-1
votes
1
answer
30
views
Sum values in one dataframe based on values of column in another dataframe
I have two dataframes that look like the following
library(dplyr)
State = c('AK','AL','AR','AZ')
Perc = c(0.0023, 0.0034, 0.0043, 0.065)
df1 <- data.frame(State, Perc)
ID = c('A','B','C','D','E')...
1
vote
4
answers
70
views
How to split datetime period data into monthyear based on unique values in a column in R
I have a series of receivers that were deployed for various periods. The dataset looks like this:
Receiver
start_dt
end_dt
1
2021-05-19 15:43:00
2022-06-19 12:43:00
2
2021-08-19 15:43:00
2022-05-10 ...
0
votes
0
answers
25
views
How to create an auto-incremental column based on two other columns in R Shiny?
I work with R Shiny.
My app imports a CSV file and just after I'd like to add a new auto-incremental column called "campagne".
With that new column, the structure of my CSV would be the one. ...
1
vote
1
answer
56
views
dplyr::left_join() produces missing values on new columns and/or duplicated columns
I'm merging two dataframe objects using dplyr's left_join() function, but it produces NA in newly created columns. Sometimes it did produce merged data with actual values but merged columns are ...
0
votes
0
answers
21
views
How do I avoid Error normalizePath with read_excel in R?
I was trying to import table from excel (xlsx) to my R, but I get an error
Warning message: In normalizePath(path.expand(path), winslash, mustWork) :
path[1]="Data_202310.xlsx": Access is ...
0
votes
0
answers
69
views
How to calculate cumulative proportion of population with the occurrence of an event over time?
I want to calculate the cumulative proportion of patients with the occurrence of an event based on a simulation.
I was expecting the output to look something like
instead I am generating the plot ...
0
votes
1
answer
44
views
How to plot every column of a data frame agains every other column using ggplot and geom point?
I have a data frame with 3 columns and I would like to plot every column versus the other column with geom_point. I am aware of ggpairs function but I would like to do this using regular geom_point().
...
0
votes
1
answer
31
views
Create a group variable first.treat indicating the first year each unit is treated
I have the following database:
ano id_mun tratado
1998 313240 0
1998 313250 0
1998 313260 1
. . .
. . .
. . .
2019 ...
0
votes
1
answer
28
views
How to make longer based on ID column, *without* collapsing the remaining columns? - R
Based on this question and answer, that is close to satisfying my needs: R - how to make long rows by matching an element of original rows
df <- data.table::data.table(ID = c(123,123,123,234,456, ...
0
votes
1
answer
30
views
Elegant way to look up and assign values from dictionary in R
I have a pair of large dataframes, taxi_origins and taxi_destinations, with lat/long variables for origins and destinations. I would like to update a few observations (those with a DC airport as an ...
0
votes
1
answer
36
views
How to change names of `map2_df` outputs
This is my code.
countries <- c("USA", "Canada", "UK", "Germany", "France")
country_data <- map(countries, ~ tibble(
Country = .,
Population ...
1
vote
3
answers
53
views
Cummean ignoring NAs and replacing NA with last valid value
Similar to this post Calculate cummean() and cumsd() while ignoring NA values and filling NAs but I would rather stick to tidyverse
My data:
structure(list(season = c("Winter", "Winter&...
0
votes
1
answer
42
views
Transforming multiple hot-encoded columns and converting to long-format
I have a quite complex data frame structure:
ID = c(1,2,3)
Sessions = c("2023-11-14 19:01:39+01:00", "2023-11-14 20:01:39+01:00", "2023-11-14 21:01:39+01:00")
P_affect =...
0
votes
1
answer
34
views
Modifying the sentiment of certain words in tidytext get_sentiments()
I am trying to modify the sentiment of a few specific words in my df to make them more suitable for my context, where they were used with a negative connotation but have been classified as having a ...
0
votes
1
answer
58
views
Mutate across multiple columns while indexing with a list column
I am trying to compute a mean across multiple columns v1 and v2 while subsetting on the index contained within another list column k. Here is a toy example.
library(dplyr)
set.seed(1452)
df <- ...
-1
votes
1
answer
41
views
How best to do this specific row operation in R?
So for this task, in my real data set. I have 18 rows that are indcode = 000000 and ownership code = 10. The differentiating factor is area. Likewise, I have 18 rows that are indcode = 4911 and ...
0
votes
1
answer
18
views
How can I conditionally sum values in R based on start/end dates in another column?
Suppose I have a table with rows for a rate, start date and end date, and I want to calculate the sum of any 'rate' values that are active on a specific day
df <- data.frame( startDate=c('2023-11-...
2
votes
1
answer
42
views
r derived indicator variable
Suppose this is my dataset.
ID Group Col1 Col2
1 A 1.49 NA
2 A 0.12 NA
2 A NA 0.35
3 B NA 0.87
4 B NA 0.64
4 B ...