I am new to R, and I have been using Stata for multiple years. I am trying to create a loop and a set of conditions within the loop that will do some recoding of data. I am, truly, lost, so any suggestions are welcomed. Please, help!
Specifically, I am trying to use conditions so R will perform actions and I am using dplyr. As you will notice from the code below. I am calling my libraries, simulating minimal data, and trying to get through a for loop where R examines multiple conditions. To initiate the conditions, I want R to capture the minimum and maximum, then, go through the conditions, and when TRUE, perform the recode procedure that creates a new variable in the data frame. Also, code is nice, but understanding is better, please help me understand what I am doing wrong with this--I am new to R.
library(tidyverse)
library(dplyr)
#my simulated data
v1 <- sample(c(0,1), 200, replace = TRUE)
v2 <- sample(c(0,1), 200, replace = TRUE)
v3 <- sample(c(1:7), 200, replace = TRUE)
v4 <- sample(c(1:5), 200, replace = TRUE)
v5 <- sample(c(1:10), 200, replace = TRUE)
v6 <- sample(c(0:200), 200, replace = TRUE)
dat<-data.frame(v1, v2, v3, v4, v5, v6)
for(m in c("v1", "v2", "v3", "v4", "v5", "v6")){
z <-get(m)
j <-min(z)
k <-max(z)
if (j == 0 & k == 1) {
dat <- dat %>% mutate(across(everything()), ifelse (z =="1", 1, 2))
} else if (j>= 1 & k <=5 {
dat <- dat %>% mutate(v4_1 = recode(v4, "1" = 2, "2" = 2, "3" = 2, "4" = 2, "5" = 2))
}
}
View(dat)
To give some perspective of how I intend this to look. Note: I haven't set a seed so these numbers are random, but I present them to provide some perspective as to how I intend this to work. After going through this code, three new variables should be created in the data frame--dat. It should look like the following:
v1 v2 v3 v4 v5 v6 v1_1 v2_1 v4_1
1 1 1 5 10 100 1 1 2
0 1 2 3 9 80 2 1 2
1 0 3 2 8 70 1 2 2
0 1 3 1 7 20 2 1 2
Please help! I am lost with this, and am open to any and all suggestions. This should get me on my way, but please help me understand with some explanation of potential code so I may be able to modify the code to be able to handle other situations.
Thank you in advance.