在“for”中引入两个字符串环形
我有这个数据框:
a <- c(2,5,90,77,56,65,85,75,12,24,52,32)
b <- c(45,78,98,55,63,12,23,38,75,68,99,73)
c <- c(77,85,3,22,4,69,86,39,78,36,96,11)
d <- c(52,68,4,25,79,120,97,20,7,19,37,67)
e <- c(14,73,91,87,94,38,1,685,47,102,666,74)
df <- data.frame(a,b,c,d,e)
和这个脚本:
R <- Map(`+`, list(1:3), 0:9)
cmin <- t(as.matrix(rep(NA, ncol(df))))
for (r in seq(R)) {
for (f in seq(ncol(df))) {
x <- df[R[[r]], f]
y <- df[R[[r]], -f]
dif_2 <- (x - y)^2
cmin[f] <- which.min(colSums(dif_2))
}
}
dif_3 <- as.matrix(dif_2[,cmin])
sq <- sqrt(dif_3)
如何将脚本的最后两行放入上面的“for”循环中?
感谢大家对我的帮助!
I have this dataframe:
a <- c(2,5,90,77,56,65,85,75,12,24,52,32)
b <- c(45,78,98,55,63,12,23,38,75,68,99,73)
c <- c(77,85,3,22,4,69,86,39,78,36,96,11)
d <- c(52,68,4,25,79,120,97,20,7,19,37,67)
e <- c(14,73,91,87,94,38,1,685,47,102,666,74)
df <- data.frame(a,b,c,d,e)
and this script:
R <- Map(`+`, list(1:3), 0:9)
cmin <- t(as.matrix(rep(NA, ncol(df))))
for (r in seq(R)) {
for (f in seq(ncol(df))) {
x <- df[R[[r]], f]
y <- df[R[[r]], -f]
dif_2 <- (x - y)^2
cmin[f] <- which.min(colSums(dif_2))
}
}
dif_3 <- as.matrix(dif_2[,cmin])
sq <- sqrt(dif_3)
How can I put the last two lines of the script into the "for" loop above?
Thanks everyone for helping me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果“ sq”的输出应为
vector
output
,如果应该是
list
If the output of 'sq' should be a
vector
-output
If it should be a
list
如果我正确理解,则需要在
r
中给出的每个行索引的最小距离。下面的代码创建两个数据结构,sq_list1
和sq_3d
存储相同的值,但一个o是矩阵列表,另一个是带有第3个索引的3D数组1:长度(R)
。编辑
似乎更简单。
If I understand correctly, you want the min distances for each row indices given in
R
. The code below creates two data structures,sq_list1
andsq_3d
that store the same values but one o them is a list of matrices and the other is a 3d array with the 3rd index1:length(R)
.Edit
This seems simpler.