简体   繁体   English

基数 R 中的行操作问题

[英]Problem with row-wise operation in base R

I have a problem with performing row-wise operations using 'apply' function in R. I want to calculate the distance between two points:我在 R 中使用“应用”函数执行逐行操作时遇到问题。我想计算两点之间的距离:

d <- function(x,y){
length <- norm(x-y,type="2")
as.numeric(length)
}

The coordinates are given by two dataframes:坐标由两个数据框给出:

start <- data.frame(
a = c(7, 5, 17, 1), 
b = c(5, 17, 1, 2))

stop <- data.frame( 
b = c(5, 17, 1, 2),
c = c(17, 1, 2, 1))

My point is to calculate successive distances given by start and stop coordiantes.我的观点是计算由开始和停止坐标给出的连续距离。 I wish it worked like:我希望它像这样工作:

d(start[1,], stop[1,])
d(start[2,], stop[2,])
d(start[3,], stop[3,])
etc...

I have tried:我试过了:

apply(X = start, MARGIN = 1, FUN = d, y = stop)

which brought some strange results.这带来了一些奇怪的结果。 Can you please help me with finding the proper solution?你能帮我找到合适的解决方案吗? I know how to perform the operation using dplyr rowwise() function, however my wish is to use base only.我知道如何使用 dplyr rowwise() 函数执行操作,但是我希望只使用 base。 Can you also explain me why did I receive such a strange results with apply()?你也能解释一下为什么我用 apply() 收到这么奇怪的结果吗?

Loop over the sequence of rows and apply the d循环遍历行序列并应用d

sapply(seq_len(nrow(start)), function(i) d(start[i,], stop[i,]))
[1] 12.165525 20.000000 16.031220  1.414214

Or if we want to use apply , create a single data by cbind ing the two data and then subset by indexing或者,如果我们想使用apply ,通过cbind两个数据创建单个数据,然后通过索引创建子集

apply(cbind(start, stop), 1, FUN = function(x) d(x[1:2], x[3:4]))
[1] 12.165525 20.000000 16.031220  1.414214

Or may use dapply for efficiency或者可以使用dapply来提高效率

library(collapse)
dapply(cbind(start, stop), MARGIN = 1, parallel = TRUE,
   FUN = function(x) d(x[1:2], x[3:4]))
[1] 12.165525 20.000000 16.031220  1.414214

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

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