简体   繁体   中英

Grouping multiple rows in R

I've generated a heatmap in R for microbiome data, using the following link

My data as far as rows is concerned looks like this:

781
782
783
547
519
575
044
045
049

If I want to group 781-783, 547-575 and 044-049 as individual groups and give them separate colours using the below idea:

Assigning animals to different groups (2 random groups in this case)

var1 <- round(runif(n=12, min=1, max=2))
var1 <- replace (var1, which(var1 == 1), "deepskyblue")
var1 <- replace (var1, which(var1 == 2), "magenta")
cbind(row.names(data.prop), var1)

How do I go about it? I understand that the above code, randomly generates 2 groups, but how can I specify which rows go into which group?

Thank you,

Susheel

Because rownames are of necessity character and the only good range-operator in R is ":" for numeric values: you need to coerce ranges to the desired "0nn" format. This is untested in the absence of a proper test case (which questioners are asked to provide):

#look at...
sprintf("%03i", c(781:783, 547:575, 044:049))
# then....

 data.prop[ sprintf("%03i", c( 781:783, 547:575, 044:049), 'var1'] <-
      mapply(function(clr, rng) {rep(clr, length(rng) )}, 
                    c("deepskyblue",  "magenta", "green"), 
                    list(  781:783, 547:575, 44:49)
              )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM