Reputation: 75
I have a problem of saving a series of vectors (column of matrix) in "for loop" in R. Actually, I want to calculate the mean of some vectors (rows) in a matrix. I ran "for loop" to find out the vectors (columns) I want to find mean for rows of those vectors (columns). I have tried to use "apply" function but what I got is the last vector (column) because I don't know how to save those previous vectors (columns) while running "for loop" in somewhere. Can anybody enlighten me? Thanks. `
column.name<-colnames(loadfile)
for(i in 1:length(column.name)){
char<- column.name[i]
tmp<-agrep("HW", char, ignore.case = TRUE, max.distance = 0.1 )
if(length(tmp) > 0){
print(column.name[i])
x<-i
print(x)
}
loadfile$newcol<-apply(loadfile[x],1,mean)
}
Above code, loadfile is data.frame and I create a new column for saving the average of each row in HW columns. I don't mind show my code.
Upvotes: 1
Views: 1312
Reputation: 121568
Very hard to help you without a reproducible example. here I guess just what you want to do. It is vectorized version, since agrep
and rowMeans
are vectorized.
tmp <- agrep("HW", column.name, ignore.case = TRUE,
max.distance = 0.1 )
loadfile$newcol <- rowMeans(loadfile[,tmp])
EDIT I add a reproducible example, and it works fine for a matrix and a data.frame:
mm <- matrix(1:25,ncol=5)
colnames(mm) <- c(paste0('HW',1:3),paste0('NO',1:2))
loadfile <- as.data.frame(mm)
column.name <- colnames(loadfile)
tmp <- agrep("HW", column.name, ignore.case = TRUE,
max.distance = 0.1 )
loadfile$newcol <- rowMeans(loadfile[,tmp])
Upvotes: 3