简体   繁体   English

从矩阵中提取观察

[英]Extract Observation from a Matrix

I have a matrix (see above).我有一个矩阵(见上文)。 I have the name of species and sub-species of plants in rows.我有一排植物的物种和亚种的名称。

I would like to generate the same matrix with only the species and a matrix with only the sub-species.我想生成只有物种的相同矩阵和只有亚种的矩阵。

The species in my initial matrix are composed of one word ( abelia , abis ) and sub-species contain always two words ( abies alba , etc).我的初始矩阵中的物种由一个词( abeliaabis )组成,而亚种总是包含两个词( abies alba等)。

How can i do that in R ?我怎么能在 R 中做到这一点?

Assuming that the matrix is called m , you can try this:假设矩阵被称为m ,你可以试试这个:

species_rows <- lengths(strsplit(rownames(m)," "))==1 #split the rownames at whitespaces, retain only rows that are not split (vector of length 1).
species_mat <- m[species_rows,] #logical subsetting
subspecies_mat <- m[!species_rows,] #logical subsetting with negation

Hat tip to @akrun for pointing out that lapply(..,length) can be replaced by lengths() . @akrun 的帽子提示指出lapply(..,length)可以替换为lapply(..,length) lengths()


Or even simpler:或者更简单:

species_rows <- !grepl(" ",rownames(m)) # does the row.name NOT contain a whitespace? (TRUE / FALSE)
species_mat <- m[species_rows,]
subspecies_mat <- m[!species_rows,]

Welcome to SO, as suggested, it would have been good if you provided sample data to your question.欢迎来到 SO,正如建议的那样,如果您为您的问题提供示例数据,那就太好了。

That said, I think you can do:也就是说,我认为你可以这样做:

# First, generate data:
a <- matrix(sample(c(0, 1), 20), ncol = 4)
rownames(a) <- c("abies", 
                 "abies alba", 
                 "abies amabilis", 
                 "abies balsamea", 
                 "abies concolor")

Then, you can use grep to find which names contain an empty space:然后,您可以使用grep查找哪些名称包含空格:

sp <- grep(" ", rownames(a))

And finally, assign to new matrixes:最后,分配给新矩阵:

subspecies <- a[sp,]
species <- a[-sp,]

As a side note, I'd recommend working with a data frame instead of a matrix, and assigning the names to a variable, instead of rownames.作为旁注,我建议使用数据框而不是矩阵,并将名称分配给变量,而不是行名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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