bvowe
bvowe

Reputation: 3384

R Recode Variables In A Loop

Ciao,

Here is a replicate able example.

df <- data.frame("STUDENT"=c(1,2,3,4,5),
                 "TEST1"=c(6,88,17,5,18),
                 "TEST2"=c(34,NA,87,88,82),
                 "TEST3"=c(87,62,13,8,71),
                 "TEST1NEW"=c(0,1,0,0,0),
                 "TEST2NEW"=c(0,NA,1,1,1),
                 "TEST3NEW"=c(1,1,0,0,1)

If I have data frame df with STUDENT, TEST1, TEST2, TEST3 I want to make TEST1NEW TEST2NEW and TEST3NEW such that the new variables are equal to 1 when old variable TEST is more than or equals to 50 and the NEW TEST variables should be equal to 0 when the old TEST variable is below 50. I made an attempt here below but this is insufficient and also I believe this may require a loop.

COLUMNS <- c("TEST1", "TEST2", "TEST3")
df[paste0(COLUMNS)] <- replace(df[COLUMNS],df[COLUMNS] < 50, 0 , 1, NA)

Upvotes: 1

Views: 402

Answers (1)

markus
markus

Reputation: 26343

You could do

df[, paste0("TEST", 1:3, "_NEW")] <- as.integer(df[,-1] >= 50)
df
#  STUDENT TEST1 TEST2 TEST3 TEST1_NEW TEST2_NEW TEST3_NEW
#1       1     6    34    87         0         0         1
#2       2    88    NA    62         1        NA         1
#3       3    17    87    13         0         1         0
#4       4     5    88     8         0         1         0
#5       5    18    82    71         0         1         1

data

df <- data.frame(
  "STUDENT" = c(1, 2, 3, 4, 5),
  "TEST1" = c(6, 88, 17, 5, 18),
  "TEST2" = c(34, NA, 87, 88, 82),
  "TEST3" = c(87, 62, 13, 8, 71)
)

In case where the assignment is more complex we can make use of dplyr::case_when

library(dplyr)
df[, paste0("TEST", 1:3, "_NEW")] <- case_when(df[,-1] < 20 ~ 4L,
                                               df[,-1] >= 65 ~ 8L,
                                               is.na(df[,-1]) ~ NA_integer_,
                                               TRUE ~ 7L)

Upvotes: 2

Related Questions