以下代码显然是错误的.有什么问题?
i <- 0.1
i <- i + 0.05
i
## [1] 0.15
if(i==0.15) cat("i equals 0.15") else cat("i does not equal 0.15")
## i does not equal 0.15
Run Code Online (Sandbox Code Playgroud) R中的基本/公共类被称为"dist",并且是对称距离矩阵的相对有效的表示."matrix"但是,与对象不同,似乎不支持"dist"使用"["运算符通过索引对操作实例.
例如,以下代码不返回任何内容NULL,或错误:
# First, create an example dist object from a matrix
mat1 <- matrix(1:100, 10, 10)
rownames(mat1) <- 1:10
colnames(mat1) <- 1:10
dist1 <- as.dist(mat1)
# Now try to access index features, or index values
names(dist1)
rownames(dist1)
row.names(dist1)
colnames(dist1)
col.names(dist1)
dist1[1, 2]
Run Code Online (Sandbox Code Playgroud)
同时,在某种意义上,以下命令可以正常工作,但不要使访问/操作特定索引对值更容易:
dist1[1] # R thinks of it as a vector, not a matrix?
attributes(dist1)
attributes(dist1)$Diag <- FALSE
mat2 <- as(dist1, "matrix")
mat2[1, 2] <- 0
Run Code Online (Sandbox Code Playgroud)
一个解决方法 - …
我想知道在某个索引处将矢量分成两个的简单任务:
splitAt <- function(x, pos){
list(x[1:pos-1], x[pos:length(x)])
}
a <- c(1, 2, 2, 3)
> splitAt(a, 4)
[[1]]
[1] 1 2 2
[[2]]
[1] 3
Run Code Online (Sandbox Code Playgroud)
我的问题:必须有一些现有的功能,但我找不到它?可能split是一种可能吗?如果pos=0或是,我的天真实施也不起作用pos>length(a).
我找到了一个 R 包Rlof,它使用多线程来计算距离矩阵,它做得很好。
但是,该函数的输出distmc是向量而不是矩阵。应用as.matrix到这个“dist”对象比距离的多线程计算要昂贵得多。
查看函数 help,打印对角线和上三角形的选项在那里,但我不明白应该在哪里使用它们。
有没有办法as.matrix以某种方式节省时间?
可重现的例子:
set.seed(42)
M1 = matrix(rnorm(15000*20), nrow = 15000, ncol =20)
system.time({dA = distmc(M1, method = "euclidean", diag = TRUE,
upper = TRUE, p = 2)})
system.time(A = as.matrix(dA))
Run Code Online (Sandbox Code Playgroud) 假设我有一个c(1, 2, 3, 4)没有重复值的向量.我需要一个向量c(1 * 2, 1 * 3, 1 * 4, 2 * 3, 2 * 4, 3 * 4),所以乘法是在这个向量值的所有可能组合中完成的.有没有办法做到这一点?提前致谢!
说我有
> x<-1:5
> dist(x)
1 2 3 4
2 1
3 2 1
4 3 2 1
5 4 3 2 1
> which(dist(x)==max(dist(x)))
[1] 4
Run Code Online (Sandbox Code Playgroud)
如何从索引4返回到行号和列号(5,1)?
我想知道如何从距离矩阵中提取第一个对角线的值.
例如:
> mymatrix
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 6 4
[4,] 8 6
> dist(mymatrix)
1 2 3
2 2.828427
3 5.385165 3.000000
4 8.062258 5.385165 2.828427
Run Code Online (Sandbox Code Playgroud)
我想在向量中得到值: 2.828427, 3.000000, 2.828427
谢谢!