[R] Odp: Extracting values in table
Petr PIKAL
petr.pikal at precheza.cz
Mon Aug 29 09:12:49 CEST 2011
Hi
> Hi All,
>
> I am a beginner in programming in r and please do forgive me if my
question
> seems to be silly and sometimes not understandable.
>
> 1. we have a list of elements in a list say:
>
> ls<-list("N","E","E","N","P","E","M","Q","E","M")
>
> 2. We have an another list of tables in a list say:
>
> n <- list("M", "N","E","P","Q","M","N","E","Q","N")
>
> tb <- lapply(1:10, function(i)matrix(sample(4), 2, 2,
> dimnames=list(n[sample(10,2)], n[sample(2,2)])))
>
> 3. we need to extract values from the table in the list where colname is
> always "M" , wherein the rowname should be the 1st element in the list
ls
> for table 1 in the list tb and 2nd element in table 2 and so on...
>
> for ex:
> M N
> N 4 1
> P 3 2
>
> In table 1 , we need to extract value 4.
I can not provide you with canned solution but
x = sapply(tb, function(x) which(dimnames(x)[[2]]=="M"))
gives you vector of M positions in column names
for (i in seq_along(ls1)) print(which(rownames(tb[[i]]) %in% ls[[i]]))
# for (i in seq_along(ls1)) y[i] <- which(rownames(tb[[i]]) %in% ls[[i]])
# does not work as there is sometimes no match
gives you position of row names (if they exist)
then you can use that for selection of items from list tb
e.g. for the first table
tb[[1]][x[1],y[[1]]]
> tb[[1]]
M N
N 3 2
Q 1 4
tb[[1]][x[1],y[1]]
[1] 3
Regards
Petr
>
>
> Thanks to all in advance.
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Extracting-
> values-in-table-tp3771272p3771272.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list