I am recoding data in R and want a basic for-loop with the following properties:
Assess every value in a vector.
If the value is not a member of a fixed set, then recode the value to 0.
For the following example code, that would mean that all 50 values in the array 'data' are assessed and will be recoded to 0, 1, 3, or 5. However, the loop stops early and only the first few numbers are recoded.
set = c(1, 3, 5)
data<-round(runif(n=50, min=1, max=8), 0)
data #initial data set
for (x in data) {
if (!(data[x] %in% set)) {
data[x]<- 0
}
}
data #recoded data
My troubleshooting: I tried to insert an else..next statement to keep the loop going.
The correct for loop is:
Use the indices of data. In your actual for loop you are using the values:
for (i in seq_along(data)) {
if (!(data[i] %in% set)) {
data[i] <- 0
}
}
#data
#recoded data
[1] 1 0 0 0 3 0 0 0 0 5 3 0 3 3 0 0 0 1 0 0 5 0 0 0 0 0 5 0 0 0
[31] 0 0 5 0 3 1 0 5 0 1 0 1 3 0 0 0 5 0 3 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments