[R] AutomaticTRUE/FALSE Matrix Generation

Sarah Goslee sarah.goslee at gmail.com
Thu Apr 28 13:18:56 CEST 2011


You don't provide a reproducible example because we don't have
any data to try, just the result dataframe. And I'll admit I got bogged
down in trying to figure out what you're doing because your lists
and columns and values are all the same pairs of characters.

On Thu, Apr 28, 2011 at 4:25 AM, ivan <i.petzev at gmail.com> wrote:
> Dear All,
> I am a newbee in R an have the following problem. I have variables AB,BC,CD
> to which outputs are assigned. Now AB[,1], for example, outputs a list,
> which is a random combination of the following characters: "AB", "BC", "CD".
> What I want to do is to build a 3x3 matrix with colnames and rownames equal
> to "AB", "BC", "CD". Matrix values TRUE or FALSE shall then be automatically
> assigned. Hence, if a colname of the matrix is represented in output AB, the
> assigned value should be TRUE and otherwise FALSE.
> I tried to do the following:
> c.matrix<-matrix(NA,ncol=3,nrow=3);
> colnames(c.matrix)<-cbind("AB", "BC", "CD");rownames(c.matrix)<-cbind("AB",
> "BC", "CD");
> c.matrix<-as.data.frame(c.matrix)
> which produces:
>        AB BC CD
> AB  NA  NA  NA
> BC  NA  NA  NA
> CD  NA  NA  NA
> Then for column AB I tried this in order to assign the TRUE/FALSE values to
> the NA matrix:
> for(i in 1:3)) {if (length(intersect(names(c.matrix)[[i]],AB[,1]))>0)
> {c.matrix[[i,1]]=TRUE} else {condition.matrix[[i,1]]=FALSE}}

I think some combination of lapply() and table() would be nicer.
Failing that, %in% might still be a more elegant solution. Again,
without data it's hard to try it.

But in this specific case, you refer to c.matrix twice and
condition.matrix (undefined) once - that could be part of your
problem. Is AB a dataframe? And I can't see why you'd need
double brackets anywhere. But don't you want row.names(c.matrix)
not names(c.matrix)?

Anyway, back to "complete reproducible example please."

Sarah Goslee

More information about the R-help mailing list