在矩阵中重复行N的值N次

编程入门 行业动态 更新时间:2024-10-25 13:23:42
本文介绍了在矩阵中重复行N的值N次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我在R中有一个如下所示的矩阵:

If I have a matrix in R that looks like the below:

1,3 7,1 8,2

我将如何编写创建如下矩阵的代码:

How would I write code that creates a matrix like this:

1,3 1,3 1,3 7,1 8,2 8,2

它根据正确的.column值在哪里重复行?请记住,我有一个矩阵,实际上它的行比2多得多.

Where it repeats the row based on the right .column value? Keep in mind I have a matrix that actually has a lot more rows than 2

推荐答案

# construct your initial matrix x <- matrix( c( 1 , 3 , 7 , 1 , 8 , 2 ) , 3 , 2 , byrow = TRUE ) # take the numbers 1 thru the number of rows.. 1:nrow(x) # repeat each of those elements this many times x[ , 2 ] # and place both of those inside the `rep` function rows <- rep( 1:nrow(x) , x[ , 2 ] ) # ..then return exactly those rows! x[ rows , ] # or save into a new variable y <- x[ rows , ]

更多推荐

在矩阵中重复行N的值N次

本文发布于:2023-11-30 20:21:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651367.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!