【问题标题】:Assigning variables from a matrix in R从R中的矩阵分配变量
【发布时间】:2014-09-13 21:30:50
【问题描述】:

我认为我从矩阵中错误地访问和分配变量。我知道数组、矩阵和表在 R 中是不同的。我想要结束的是一个名为“c”的值数组,它有一个 1 或 2,将输入中的元素分配给 Mew(number 1) 或Mewtwo(编号 2。我还想要从 Mew 到名为 dMew 的数组中的所有其他点的距离以及 dMewtwo 从 Mewtwo 到输入中所有其他元素的距离的数组。我最终得到的是 NA_real_ 对于所有变量,除了输入。有很多关于访问 R 中各种数据结构的行或列的重要信息,但我对访问单个元素感兴趣。任何建议都会很有帮助。如果之前已经回答过,我很抱歉,但我不能在任何地方都可以找到它。

#Read input from a csv data file
input = read.csv("~/Desktop/Engineering/iris.csv",head=FALSE)
input = input[c(0:3)]
input = as.matrix(input)

#set random centroids
Mew = input[1,1]
Mewtwo = input[nrow(input),ncol(input)]

#Determine Distance
dist <- function(x, y) {
  return(sqrt((x - y)^2))
}

#Determine the clusters
dMew = matrix(,nrow(input), ncol(input))
dMewtwo = matrix(,nrow(input), ncol(input))
c = matrix(,nrow(input), ncol(input))
for (i in 1:nrow(input)) {
  for (j in 1:ncol(input)) {
    dMew[i,j] = dist(Mew, input[i,j])
    dMewtwo[i,j] = dist(Mewtwo, input[i,j])
    if (dMew[i,j] > dMewtwo[i,j]) {
      c[i,j] = 2
    } else {
      c[i,j] = 1
    }
  }
}

#Update the centroids
Mew = mean(dMew)
Mewtwo = mean(dMewtwo)

【问题讨论】:

  • 您的 for 循环仅迭代 nrow(input)ncol(input) 而不是 1:nrow(input)1:ncol(input)。尝试使您的代码可重现并将其减少为主要问题,例如,我们无权访问您的数据源。
  • 是的,我发帖后注意到了。
  • 您的dist 函数返回x - y,因为您忘记使用sum。你能提供一些数据来处理吗?

标签: arrays r matrix


【解决方案1】:

使用以下输入运行代码没有问题:

input = data.frame(V1=1:5,V2=1:5,V3=1:5)

所以这似乎是与您的数据有关的问题。此外,您应该避免使用“c”作为变量名,并注意 dist() 已经是 stats 包中的一个函数。此外,您可以使用 apply() 和 ifelse() 来避免 for 循环:

#Read input from a csv data file
input = data.frame(V1=1:5,V2=1:5,V3=1:5)
input = input[c(1:3)]
input = as.matrix(input)

#set random centroids
Mew = input[1,1]
Mewtwo = input[nrow(input),ncol(input)]

#Determine Distance
dist.eu <- function(x, y) {
  return(sqrt((x - y)^2))
}

dMew<-apply(input,c(1,2),dist.eu,Mew)
dMewtwo<-apply(input,c(1,2),dist.eu,Mewtwo)

c.mat<-ifelse(dMew > dMewtwo,2,1)
c.mat

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 2012-07-10
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2019-11-09
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多