[R] How to get rid of my for loop
Barry King
barry.king at qlx.com
Mon Sep 29 11:59:02 CEST 2014
# Here are sample data, sample vectors, and a for loop
# that I am using now. I wish to get rid of the for loop
# and use functions and one of the apply functions to
# perform the work without needing a many iteration for loop.
A_01 <- 1:5
A_02 <- 6:10
A_03 <- 11:15
A_04 <- 16:20
B_01 <- 101:105
B_02 <- 106:110
B_03 <- 111:115
B_04 <- 116:120
# I am showing just two pairs, A_x with A_array and B_x with B_array.
# In actuality there are about a dozen such pairings.
A_array <- array(NA, dim=5)
B_array <- array(NA, dim=5)
VFD_ID <- c(3, 2, NA, 1, 3)
nobs <- length(VFD_ID)
# This for loop works fine but is not appropriate for
# a large number of observations in VFD_ID.
for (i in 1:nobs){
if (is.na(VFD_ID[i])){
A_array[i]<- 0
B_array[i]<- 0
} else if (VFD_ID[i] == 1){
A_array[i]<-A_01[i]
B_array[i]<-B_01[i]
} else if (VFD_ID[i] == 2){
A_array[i]<-A_02[i]
B_array[i]<-B_02[i]
} else if (VFD_ID[i] == 3){
A_array[i]<-A_03[i]
B_array[i]<-B_03[i]
} else if (VFD_ID[i] == 4){
A_array[i]<-A_04[i]
B_array[i]<-B_04[i]
}
}
# This does NOT work. It returns the entire vector,
# not just the corresponding element in VFD_ID.
# (Note: It seems like a switch function would work here
# but I was unable to get it to work correctly.)
A_array_fnc <- function(x){
if (is.na(x)) return (0) else
if (x == 1) return (A_01) else
if (x == 2) return (A_02) else
if (x == 3) return (A_03) else
if (x == 4) return (A_04)
}
B_array_fnc <- function(x){
if (is.na(x)) return (0) else
if (x == 1) return (B_01) else
if (x == 2) return (B_02) else
if (x == 3) return (B_03) else
if (x == 4) return (B_04)
}
A_array <- sapply(VFD_ID,A_array_fnc)
B_array <- sapply(VFD_ID,B_array_fnc)
# Is there a way to write the functions correctly so that
# the return value for, say A_array[4] is A_03[4] if VFD_ID == 3?
# Any assistance is greatly appreciated.
More information about the R-help
mailing list