[R] Odp: nesting multiple for loops
petr.pikal at precheza.cz
Fri Apr 15 12:18:54 CEST 2011
r-help-bounces at r-project.org napsal dne 15.04.2011 01:34:22:
> Hi everyone.
> I am quite frustrated that this doesn't work, as all the functions
> work fine by themselves. I'd also like any pointers to how to avoid
> loops in my code. I understand it's less than desirable, but I'm still
> new and use them a lot.
> I have a few wide datasets (90 to 120) with long column names, each name
> contains a number of different 'markers'. Each could be considered a
> variable within the column name. Their are two categories of factors,
> call them f1 and f2.
> The data frame names look something like this:
> 'ace_van' , 'boy_van', 'car_xes' , 'ace_xes', 'dog_wall' , 'car_zounds'
> f1 <- c('ace', 'boy', 'car', 'dog')
> f2 <- c('van', 'wall', 'xes', 'zounds') # actual vectors are length 6
> 7, so I don't want to individually sum the 42 combinations.
> > var.table <- function(data, vec1, vec2)
> table <- as.data.frame(matrix(nrow = length(vec1), ncol =
> row.names = vec1)
> names(table) <- vec2
> for (i in 1:length(vec1))
> for (j in 1:length(vec2))
> indices <- intersect(grep(vec1[j], names(data), value = TRUE),
> grep(cats[i], names(data), value = TRUE))
> table[i,j] <- sum(data[ ,indices])
> > var.table(mydf, f1, f2)
> Error in FUN(X[[1L]], ...) :
> only defined on a data frame with all numeric variables
> Every entry in mydf is an integer with no missing values.
I can not provide solution as I can not decipher what you want to do but
here are few comments.
Do not use names of functions for naming objects e.g. table, it can be
What is cats??
Are you sure that mydf values are numbers?
What does str(mydf) say?
Do I understand that you want summarise all values in columns of data
frame that have some common name?
lapply(f2, grep, names(mydf))
will give you list of indices of columns in mydf matching particular f2
item. From this you can continue. Maybe plyr package can also be used.
> Thanks a ton.
> [[alternative HTML version deleted]]
> R-help at r-project.org mailing list
> PLEASE do read the posting guide
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help