pkfly103
pkfly103

Reputation: 101

no 'dimnames' attribute for array

I'm trying to run the following R code:

X <- matrix(0, n_countries, n_languages)
for (index in 2:n_edges)
{
  i <- edgelist[index, 1]
  j <- edgelist[index, 2]
  perc <- edgelist[index, 3]
  if (perc > 0 ) 
    X[i,j] = 1

}

edgelist is a .csv file I've read in and the first few rows look like this:

                   V1  V2    V3
1   % bip posweighted  NA    NA
2                  31  18 1.000
3                 221  28 0.018
4                 185  12 0.000
5                  38  87 0.031

R says there's an error in the if statement,

Error in `[<-`(`*tmp*`, i, j, value = 1) : 
no 'dimnames' attribute for array

I've tried to apply the following solutions:

  1. Removing the first row, with the NA values with

    edgelist <- edgelist[-c(1),]

  2. And changing the column names to integers with

    colnames(edgelist) <- c(1,2,3)

None of these seem to work, as I keep getting the same error. I'm really unsure of how to solve this, as I don't understand why the for loop isn't just reading the rows into the matrix. Any advice would be greatly appreciated.

Upvotes: 0

Views: 2362

Answers (1)

Michael Barrowman
Michael Barrowman

Reputation: 1191

You'd need to convert the first column from character to numeric after removing the first row.

edgelist[,1] <- as.numeric(edgelist[,1])

Once you've removed the first row, be sure to change your for() loop to run from 1:n_edges instead of 2:n_edges

Another faster solution would come from the Matrix package by using the sparseMatrix() function to create a matrix like this. For this function, you give it your row index, column index and value that you want to put in there and it'll create the matrix for you. Although to use it, you might have to convert it from a dgCMatrix to a regular matrix:

install.packages("Matrix")
library(Matrix)
Y <-   sparseMatrix(
         i = edgelist[,1],
         j = edgelist[,2],
         x = 1*(edgelist[,3] > 0)
       )
Y <- as.matrix(Y)

Upvotes: 1

Related Questions