简体   繁体   English

使用R中的n个连续行遍历矩阵

[英]Loop over matrix using n consecutive rows in R

I have a matrix that consists of two columns and a number (n) of rows, while each row represents a point with the coordinates x and y (the two columns). 我有一个由两列和一行(n)行组成的矩阵,而每一行代表一个坐标为x和y的点(两列)。 This is what it looks ( LINK ): 这是它的外观( LINK ):

V1  V2
146 17
151 19
153 24
156 30
158 36
163 39
168 42
173 44
...

now, I would like to use a subset of three consecutive points starting from 1 to do some fitting, save the values from this fit in another list, an den go on to the next 3 points, and the next three, ... till the list is finished. 现在,我想使用从1开始的三个连续点的子集进行拟合,将来自该拟合的值保存在另一个列表中,然后继续进行下3个点,再进行下三个点,直到列表已完成。 Something like this: 像这样:

Data_Fit_Kasa_1 <- CircleFitByKasa(Data[1:3,])
Data_Fit_Kasa_2 <- CircleFitByKasa(Data[3:6,])
....
Data_Fit_Kasa_n <- CircleFitByKasa(Data[i:i+2,])

I have tried to construct a loop, but I can't make it work. 我试图构造一个循环,但无法使其正常工作。 R either tells me that there's an "unexpected '}' in "}" " or that the "subscript is out of bonds". R要么告诉我在“}”中有一个“意外的'}',要么是“下标没有联系”。 This is what I've tried: 这是我尝试过的:

minimal runnable code 最小的可运行代码

install.packages("conicfit")
library(conicfit) 

CFKasa <- NULL   
Data.Fit <- NULL

for (i in 1:length(Data)) {
  row <- Data[i:(i+2),]
  CFKasa <- CircleFitByKasa(row)
  Data.Fit[i] <- CFKasa[3]
}

RStudio Version 0.99.902 – © 2009-2016 RStudio, Inc.; Win10 Edu.

The third element of the fitted circle (CFKasa[3]) represents the radius, which is what I am really interested in. I am really stuck here, please help. 拟合圆的第三个元素(CFKasa [3])表示半径,这是我真正感兴趣的半径。我真的被困在这里,请帮忙。

Many thanks in advance! 提前谢谢了!

Best, David 最好的,大卫

Turn your data into a 3D array and use apply : 将您的数据转换为3D数组并使用apply

DF <- read.table(text = "V1  V2
                 146 17
                 151 19
                 153 24
                 156 30
                 158 36
                 163 39", header = TRUE)
a <- t(DF)
dim(a) <-c(nrow(a), 3, ncol(a) / 3)
a <- aperm(a, c(2, 1, 3))
# , , 1
# 
#      [,1] [,2]
# [1,]  146   17
# [2,]  151   19
# [3,]  153   24
# 
# , , 2
# 
#      [,1] [,2]
# [1,]  156   30
# [2,]  158   36
# [3,]  163   39

center <- function(m) c(mean(m[,1]), mean(m[,2]))

t(apply(a, 3, center))
#     [,1] [,2]
#[1,]  150   20
#[2,]  159   35

center(DF[1:3,])
#[1] 150  20

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

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