calculation on variable with numeric prefix

iam working on a data with repeated same variable prefix, i want to perform calculations on the varible and mutate new variable based on some conditions, this is my stata codes how can i do this in R

sort patid

foreach var of varlist issuedate_n*{

by patid: egen presc_var'=count(var') if `var'<admidate_n

}

I'm not sure what the stata code is, but I'm assuming that you have a dataframe called 'Patid' and that you are creating a running count if issuedate_n is greater than admidate_n?

Maybe this code would be helpful:

library(tidyverse)
patid %>% 
  mutate(presc_var = if_else(issuedate_n < admidate_n, 1, 0)) %>% 
  mutate(presc_var_running_count = sumsum(presc_var))

It's read:
"Use the datatable 'patid',
then,
make or change the variable 'presc_var' by placing a one if the condition is true or or zero if false,
then,
make or change the variable 'presc_var_running_count' by running a cumulative summation of whatever is now in presc_var".

Thank you for your response.
My problem is I have svereal coumn for issuedate_n each ends with different number ranging from (1_515) and I want to check at one go and create a new variable if condition met. I cant just write issuedate_n because I have several number of columns


(mydata <- data.frame(
  abc = 1:5,
  def = 10:6,
  test_against = c(1,7,3,8,9)
))

library(tidyverse)

#hardcoding
mydata %>% 
  mutate(presc_var = if_else(abc < test_against, 1, 0)) %>% 
  mutate(presc_var_running_count = cumsum(presc_var))

#simplified
mydata %>% 
  mutate(presc_var_running_count = cumsum(if_else(abc < test_against, 1, 0)))

#dynamic
mydata %>% 
  mutate(across(-test_against,
                 ~ cumsum(if_else( .x < test_against, 1, 0)),
                .names = "result_{col}"))
1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.