简体   繁体   中英

Updating matrix elements in R

I'm new to R and have been running into some trouble with updating matrix elements. The code I'm working with is along these lines:

library(lubridate)
library(Hmisc)

file=read.csv(filename)
rows<-unique(file$A)
columns<-unique(file$B)
mat<-matrix(0, nrow=length(unique(file$A)), ncol=length(unique(file$B)))
rownames(mat)<-rows
colnames(mat)<-columns

This is a pretty straightforward setup. The file has several columns. What I want is to form a matrix of two of the columns. One column will serve as the rows of the matrix and the other will serve as the columns. An example would be the file containing various information about airplane flights and column A refers to origin of the flight while column B refers to destination of the flight. Thus, the matrix would be a matrix of origin and destinations where each element would be the number of flights from the specific origin to the specific destination. Since I'm new to R, I tried my approach on a limited part of the original file:

for (i in 1:10){
  inc(mat[(file[i,]$A),(file[i,]$B)])<-1
}

The inc function is part of the Hmisc library and it is used to increment variables.

When I run the following print statements for example:

print(mat[(file[2,]$A),(file[2,]$B)])
print(mat["Origin2", "Destination2"])

The first one outputs 1, while the second one outputs 0. I do not understand why this is happening because the two indexes in the print statement refer are the same.

In addition, I also ran the for loop for all the rows of the file and then wrote the matrix into a csv file. When I examine the csv file, I see that I am getting seemingly arbitrary results. For the most part, the elements are zero but occasionally there are non-zero elements. When I cross-check the non-zero elements with the original file; however, I get different answers. For instance, one element in the matrix is 38, but when I check the original file there is only 1 entry corresponding to the same origin and destination.

Any insight on why this would be happening would be much appreciated.

Try to make your question reproducible. I think this could help:

origins <- c("A", "B", "C", "D", "A", "B", "A", "B", "E", "D")
dests   <- c("X", "Y", "Z", "X", "U", "V", "X", "T", "Y", "X")

df <- data.frame(origins, dests)
df
#    origins dests
# 1        A     X
# 2        B     Y
# 3        C     Z
# 4        D     X
# 5        A     U
# 6        B     V
# 7        A     X
# 8        B     T
# 9        E     Y
# 10       D     X

table(df$origins, df$dests)
#   T U V X Y Z
# A 0 1 0 2 0 0
# B 1 0 1 0 1 0
# C 0 0 0 0 0 1
# D 0 0 0 2 0 0
# E 0 0 0 0 1 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM