[R] FYI: matrix surprise

Mario Valle mvalle at cscs.ch
Wed Jul 14 07:49:45 CEST 2010


  Some time ago someone asked for things that make R difficult to 
master. Here I want to record one R behavior that took me off-guard 
yesterday. Moral of the story: vectorialize, but don't exaggerate.
Hope it helps
                                 mario

### A very simple data frame
tc <- textConnection(
"prefix idx val
A 1 11
A 2 22
B 1 33
B 2 44")
s <- read.table(tc, stringsAsFactors=FALSE, header=TRUE)
close(tc)
print(s)

### Matrix I want to fill with the data frame values
y <- matrix(NA, 2, 2)
colnames(y) <- c("A", "B")

### This does not work. Same values in both columns
y[s$idx, s$prefix] <- s$val
print(y)

### This works as expected
for(i in 1:4) y[s$idx[i], s$prefix[i]] <- s$val[i]
print(y)

### And also this
y[s$idx[c(1,2)], "A"] <- s$val[c(1,2)]
y[s$idx[c(3,4)], "B"] <- s$val[c(3,4)]
print(y)

-- 

Ing. Mario Valle
Data Analysis and Visualization Group            | http://www.cscs.ch/~mvalle
Swiss National Supercomputing Centre (CSCS)      | Tel:  +41 (91) 610.82.60
v. Cantonale Galleria 2, 6928 Manno, Switzerland | Fax:  +41 (91) 610.82.82



More information about the R-help mailing list