[R] FYI: matrix surprise

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Jul 14 08:18:10 CEST 2010


Better moral: read the basic documentation.  You missed matrix 
indexing (indexing an array with a matrix subscript), and that is 
described in 'An Introduction to R', section 5.3

E.g.

s$p <- match(s$prefix, colnames(y))
y[cbind(s$idx, s$p)] <- s$val

(You are trying to use different types of indices for rows (integers) 
and columns (strings), and at some point strings need to be turned 
into numbers.)


On Wed, 14 Jul 2010, Mario Valle wrote:

> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list