SASnR Home

Arrays - Example - replace a value in all numeric variables


SAS

data numericdata;
infile datalines dlm='|' dsd missover;
input var1 : best32. var2 : best32. var3 : best32. var4 : best32. var5 : best32.;
label ;
format ;
datalines4;
9909|1|2|3|4
5|9909|6|7|8
9|3|9909|2|7
;;;;
run;


data numericdata01;
    set numericdata;

    array xnum[*] _numeric_;

    do i=1 to dim(xnum);
        if xnum[i]= 9909 then xnum[i]=0;
    end;

    drop i;
run;

 

Description:

  • It creates a new SAS dataset named numericdata01.
  • It uses the set statement to read data from the existing dataset numericdata.
  • An array named xnum is defined to hold all the numeric variables in the dataset. The [*] modifier indicates that the array should include all numeric variables.
  • A do-loop is used to iterate over each element of the xnum array.
  • Within the loop, an if statement checks if the current element of xnum is equal to 9909.
  • If the condition is true, the value of the current element is set to 0 using the assignment statement xnum[i]=0.
  • The drop statement is used to remove the temporary loop index variable i from the final dataset.
  • The run statement signifies the end of the data step.

R tidyverse


 

library(tidyverse)

numericdata<-tribble(
~var1,~var2,~var3,~var4,~var5,
9909,1,2,3,4,
5,9909,6,7,8,
9,3,9909,2,7,
)


numericdata01 <- numericdata %>%
  mutate(across(where(is.numeric), ~ if_else(. == 9909, 0, .)))

  

 

Description:

  • It creates a new data frame named numericdata01.
  • It uses the %>% operator to pipe the data frame numericdata into the subsequent operations.
  • The mutate() function is used to modify the data frame by applying transformations to selected columns.
  • The across() function is used to specify the columns on which the mutation should be applied. In this case, it selects all columns where the values are numeric using the where(is.numeric) condition.
  • The ~ if_else(. == 9909, 0, .) expression is a formula that defines the mutation for each selected column.
  • It checks if the current value in the column is equal to 9909 using the == operator.
  • If the condition is true, it replaces the value with 0; otherwise, it keeps the original value.
  • The resulting data frame, numericdata01, contains the original data with the specified replacements.
 

 


SASnR Home