I'm still a bit of a novice R
user, and I'm trying to run the following a number of times, each time storing a new variable into my data frame:
#Create data frame
ID <- c(286, 352, 477, 570, 870)
AV <- c(2, 3, 3, 2, 2)
AV2 <- c(1, 2, 2, 3, 3)
mydata <- data.frame(ID, AV, AV2)
Here's the key part that I want to set up in a loop:
mydata$NEWAV.1 <- mydata$AV
switch <- sample(which(mydata$AV == 2), 45, replace = FALSE)
mydata.switch <- mydata[switch,]
mydata.stay <- mydata[-switch,]
mydata.switch$NEWAV.1 <- mydata.switch$AV2
mydata <- rbind(mydata.stay, mydata.switch)
mydata <- mydata[order(mydata$ID),]
My intent is to have a bunch of NEWAV.# variables in my data frame. So if I loop this over 100 times, I'd have NEWAV.1 to NEWAV.100 variables.
Here's my attempt. Unfortunately, I'm having trouble storing those new variables into the data frame.
#Doing it 3 times for testing purposes
for (i in 1:3){
switch <- sample(which(mydata$AV == 2), 45, replace = FALSE)
mydata.switch <- mydata[switch,]
mydata.stay <- mydata[-switch,]
cbind(assign(paste0("NEWAV.", i), mydata$AV), mydata)
cbind(assign(paste0("NEWAV.", i), mydata.switch$AV2), mydata.switch)
mydata <- rbind(mydata.stay, mydata.switch)
mydata <- mydata[order(mydata$ID),]
}