[R] Behaviors of diag() with character vector in R 3.0.0
arun
smartpink111 at yahoo.com
Tue Apr 9 16:14:53 CEST 2013
Hi,
You could try this:
v <- c("a", "b")
mat1<-diag(length(v))
diag(mat1)<- v
mat1
# [,1] [,2]
#[1,] "a" "0"
#[2,] "0" "b"
v1<- letters[1:5]
mat2<- diag(length(v1))
diag(mat2)<- v1
mat2
# [,1] [,2] [,3] [,4] [,5]
#[1,] "a" "0" "0" "0" "0"
#[2,] "0" "b" "0" "0" "0"
#[3,] "0" "0" "c" "0" "0"
#[4,] "0" "0" "0" "d" "0"
#[5,] "0" "0" "0" "0" "e"
A.K.
----- Original Message -----
From: Mike Cheung <mikewlcheung at gmail.com>
To: r-help <r-help at r-project.org>
Cc:
Sent: Tuesday, April 9, 2013 3:15 AM
Subject: [R] Behaviors of diag() with character vector in R 3.0.0
Dear all,
According to CHANGES IN R 3.0.0:
o diag() as used to generate a diagonal matrix has been re-written
in C for speed and less memory usage. It now forces the result
to be numeric in the case diag(x) since it is said to have 'zero
off-diagonal entries'.
diag(x) does not work for character vector in R 3.0.0 any more. For example,
v <- c("a", "b")
## R 2.15.3
diag(v)
[,1] [,2]
[1,] "a" "0"
[2,] "0" "b"
## R 3.0.0
diag(v)
[,1] [,2]
[1,] NA 0
[2,] 0 NA
Warning message:
In diag(v) : NAs introduced by coercion
Regarding the character matrix, it still works. For example,
m <- matrix(c("a", "b", "c", "d"), nrow=2)
diag(m)
## Both R 2.15.3 and 3.0.0
[1] "a" "d"
n <- matrix(0, ncol=2, nrow=2)
diag(n) <- v
n
## Both R 2.15.3 and 3.0.0
[,1] [,2]
[1,] "a" "0"
[2,] "0" "b"
I understand that the above behavior follows exactly what the manual says.
It appears to me that the version in 2.15.3 is more general as it works for
both numeric and character vectors and matrices, whereas the version in
3.0.0 works for character matrices but not character vectors.
Would it be possible to retain the behaviors of diag() for character
vectors? Thanks.
Mike
--
---------------------------------------------------------------------
Mike W.L. Cheung Phone: (65) 6516-3702
Department of Psychology Fax: (65) 6773-1843
National University of Singapore
http://courses.nus.edu.sg/course/psycwlm/internet/
---------------------------------------------------------------------
[[alternative HTML version deleted]]
______________________________________________
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.
More information about the R-help
mailing list