如何在R

时间:2019-03-18 18:52:14

标签: r

我有一个没有名字的矩阵,如下所示:

>my_matrix
                        [,1]         [,2]         [,3]                  
ENSG00000000345 1.324266e+03 1.071842e+03 1.024920e+03 
ENSG00000000105 3.750147e+01 8.081121e+02 4.736242e+01 
ENSG00000000719 3.216755e+03 2.001329e+03 1.934501e+03 

共有280列和数千行。

我还有两个元素向量的列表,如下所示:

> head(mapping)
[[1]]
[1] "100"        "bob"

[[2]]
[1] "10"         "alice"

[[3]]
[1] "1"          "mark"

[[4]]
[1] "101"        "simon"

[[5]]
[1] "102"        "jeff"

[[6]]
[1] "103"        "alexander"

列表中有280个向量。每个向量中的第一个元素是数字1到280。第二个元素是唯一的字符串。

我想使用每个向量的第一个元素对应矩阵的列索引,使矩阵的别名成为映射列表中的唯一字符串(每个向量的第二个元素)。

例如,第1列将是“标记”。

我为向量的顺序不对应矩阵列索引而苦苦挣扎。如果是这样的话,这样的事情会起作用:

 colnames(my_matrix) <- lapply(mapping, `[[`, 2)

有人可以帮忙吗?预先谢谢你。

3 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

names.vec = sapply(mapping, unlist)[2,]
> names.vec
[1] "bob"       "alice"     "mark"      "simon"     "jeff"      "alexander"

然后将它们分配为矩阵的列名

colnames(my_matrix) = names.vec

使用示例数据的前6个条目:

mapping = list()

mapping[[1]] = c("100", "bob")
mapping[[2]] = c("10", "alice")
mapping[[3]] = c("1", "mark")
mapping[[4]] = c("101", "simon")
mapping[[5]] = c("102", "jeff")
mapping[[6]] = c("103", "alexander")
> mapping
[[1]]
[1] "100" "bob"

[[2]]
[1] "10"    "alice"

[[3]]
[1] "1"    "mark"

[[4]]
[1] "101"   "simon"

[[5]]
[1] "102"  "jeff"

[[6]]
[1] "103"       "alexander"

names.vec = sapply(mapping, unlist)[2,]
> names.vec
[1] "bob"       "alice"     "mark"      "simon"     "jeff"      "alexander"

colnames(my_matrix) = names.vec

答案 1 :(得分:0)

您可以获取索引的数字并将其放入向量中,并与名称进行相同的操作,然后将其放入矩阵的同名物中,如下所示:

import re

regex = r"([45]G).*?([\d.]+).*?([\d.]+)"

test_str = "Put in 3 extenders but by the 4th floor it is weak on signal these don't piggy back of each other. ST -99. 5G DL 624.26 UP 168.20 4g DL 2 Up .44"

matches = re.finditer(regex, test_str, re.IGNORECASE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

答案 2 :(得分:0)

@akrun在评论中正确回答了这个问题。代码:

m1 <- do.call(rbind, mapping); colnames(my_matrix)[as.numeric(m1[,1])] <- m1[,2]