[英]Problem with row-wise operation in base R
我在 R 中使用“應用”函數執行逐行操作時遇到問題。我想計算兩點之間的距離:
d <- function(x,y){
length <- norm(x-y,type="2")
as.numeric(length)
}
坐標由兩個數據框給出:
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))
我的觀點是計算由開始和停止坐標給出的連續距離。 我希望它像這樣工作:
d(start[1,], stop[1,])
d(start[2,], stop[2,])
d(start[3,], stop[3,])
etc...
我試過了:
apply(X = start, MARGIN = 1, FUN = d, y = stop)
這帶來了一些奇怪的結果。 你能幫我找到合適的解決方案嗎? 我知道如何使用 dplyr rowwise() 函數執行操作,但是我希望只使用 base。 你也能解釋一下為什么我用 apply() 收到這么奇怪的結果嗎?
循環遍歷行序列並應用d
sapply(seq_len(nrow(start)), function(i) d(start[i,], stop[i,]))
[1] 12.165525 20.000000 16.031220 1.414214
或者,如果我們想使用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
或者可以使用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.