I am trying to manipulate two dataframes called df1 and df2, which have the following structures:
df1 <- data.frame(center_x = c(1, 2, 3),
center_y = c(4, 5, 6),
label = c(1, 2, 3))
df2 <- data.frame(x = c(1, 2),
y = c(1, 1),
name = c("A", "B"))
I also have this formula euc.dist
euc.dist <- function(v1, v2){
x.val <- ( v1[1] - v2[1] )^2
y.val <- ( v1[2] - v2[2] )^2
d.val <- sqrt( x.val + y.val )
## Add d.val to v1 input as column d.val
out.df <- cbind(v1, as.numeric(d.val))
## Rename the last column of out.df as d.val
names(out.df)[length(out.df)] <- "d.val"
## Return out.df
return(out.df)
}
I want to have an output that looks like this across all the values in df1, stored as df3
R Code
x <- euc.dist(v1 = df1[1, ], v2 = df2[1, ])
y <- euc.dist(v1 = df1[1, ], v2 = df2[2, ])
df3 <- rbind(x , y)
df3
center_x center_y label d.val
1 1 4 1 3.000000
2 1 4 1 3.162278
I tried using apply, but it does not look like this:
> apply(df1, 1,
+ function (x) euc.dist(v1 = x,
+ df2[1, ])) |>
+ t()
How can I change this apply() function?