在矩阵的一个单元格中的两个值中调用一个值

call a value among two values in one cell in a matrix

有两个向量 x: 1 3 5 7 & y: 2 4 6 8。我使用函数 outer 从两个向量中元素之间的所有可能组合构建了一个 matrix(4*4),例如:

x<-c(1,3,5,7)
y<-c(2,4,6,8)
comb<-outer(x,y, paste, sep=".")
> comb
     [,1]  [,2]  [,3]  [,4] 
[1,] "1.2" "1.4" "1.6" "1.8"
[2,] "3.2" "3.4" "3.6" "3.8"
[3,] "5.2" "5.4" "5.6" "5.8"
[4,] "7.2" "7.4" "7.6" "7.8"

我现在不知道是否可以索引一个单元格中的一个元素,例如,如果有办法只调用第一个单元格 comb[1,1] 中的 element 2 有没有类似 comb[[1,1]][2]=2 "I know it is not working"

如果这不可能以这种方式实现,是否有另一种方法可以从组合中构建矩阵,然后能够单独调用和索引每个元素?

顺便说一句:我处理图形和顶点向量,所以如果还有其他类似图形的函数,请指导我。

谢谢

我认为 outer 可以很好地满足您的需求。要从矩阵中获取第二个元素,请像这样使用 substr:

substr(comb[1,1],3,3)

请注意,我选择了 3,因为它是您需要的字符的第 3 个元素。

如果矩阵中的数字超过 1 位,您也可以使用 strsplit

unlist(strsplit(comb[1,1], ".", fixed = T))[2]

编辑

如果将矩阵更改为向量,它会像这样

vector_comb = c(comb)
sapply(1:length(vector_comb), function(x) unlist(strsplit(comb[x], ".", fixed = T))[2])

这是您需要的吗?通过使用 Vectorize

comb<-outer(x,y, Vectorize( function(a,b) c( as.list(a), as.list(b) ),SIMPLIFY = FALSE))
comb
     [,1]   [,2]   [,3]   [,4]  
[1,] List,2 List,2 List,2 List,2
[2,] List,2 List,2 List,2 List,2
[3,] List,2 List,2 List,2 List,2
[4,] List,2 List,2 List,2 List,2
comb[[1,1]][2]
[[1]]
[1] 2

comb[[1,1]][1]
[[1]]
[1] 1

更新:

unlist(strsplit(comb[1,1],'.',fixed = T))[1]
[1] "1"