R: Appending values from row values specified by other row values to a list -


i have data frame 2 columns - group number , name:

group    name 1        4        b 2        c 3        d 4        e 

i want make list containing names have groups in common.

i have tried loop:

myfun <- function(x,g1,g2,g3,g4){     (j in 1:nrow(x)){         if (x[1,j] == 1){             list(g1, list(c=x[2,j]))         } else if (x[1,j] == 2){             list(g2, list(c=x[2,j]))         } else if (x[1,j] == 3){             list(g3, list(c=x[2,j]))         } else if (x[1,j] == 4){             list(g4, list(c=x[2,j]))         }                    }   } 

where g1, g2, g3 , g4 empty lists. error error in if (x[1, i] == 1) { : argument of length zero. have right approach?

edit: how can search , extract level value in list (lets want group name b in it?

you can simplify code (avoiding loops) using apply function (dat data)

res <- lapply(unique(dat$group), function(g) unique(dat[dat$group==g, "name"])) names(res) <- unique(dat$group) res[["4"]] # [1] b e # levels: b c d e 

this creates list indices of list correspond unique(dat$group) , each element contains unique "name"s in group.

another solution, using plyr

library(plyr) res <- dlply(dat, .(group), function(x) unique(x$name)) res[["4"]] # [1] b e # levels: b c d e  ## if want extract groups "b" name inds <- unlist(lapply(res, function(x) "b" %in% x)) inds #     1     2     3     4  # false false false  true   ## , extract group names(inds)[inds] # [1] "4" 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -