user3008056
user3008056

Reputation:

How to extract NA from character vector

i actually try to produce a formula from all possible combinations of features. Here is a sample code

namen<-expand.grid(c("weight",NA), c("height",NA),c("width",NA),c("volume",NA), stringsAsFactors=FALSE)
namen2<-as.data.frame(namen)

gives me a data frame with all possible combinations of the features WEIGHT, HEIGHT, WIDTH and VOLUME

for(i in 1:nrow(namen2)){  assign(paste("a", i, sep = ""), namen2[i,])}

does give me vectors with the desired combinations

for example

a7
a7q<-t(as.data.frame(a7[!is.na(a7)]))
a7q
a7f<-as.formula(paste("type~",paste(a7q,collapse="+")))
a7f

is fine

but i have no clue how to do this in a loop for all possible combinations.

This is my try:

for(i in 1:nrow(namen2)){assign(paste("a", i,"q", sep = ""), {eval(parse(text=paste("a",i,sep="")[!is.na(paste("a",i,sep=""))]))})}

But this includes NAs

Do you have any idea??

Upvotes: 0

Views: 79

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

The following code will return a list with formulas of all possible combinations based on namen:

l <- apply(head(namen, -1), 1, function(x)
               reformulate(paste(na.omit(x), collapse = "+"), response = "type"))

You can access the list elements of list l with [[, e.g., l[[1]] returns

type ~ weight + height + width + volume
<environment: 0x104298318>`

Upvotes: 1

Related Questions