Re: [R] matrix rows to single numeric element
> This seems to work: > > apply(mat1,1,function(x){paste(x,collapse="")}) > > The collapse command inside of paste is (I think) the easiest way to > combine strings. > > Michael Weylandt > > > On Thu, Aug 4, 2011 at 5:45 PM, Wegan, Michael (DNRE) > wrote: > >> I have a matrix of 5 columns and 64 rows, let's call it "mat1". All >> values are 1 or 0. I need to take the values of the elements by row and >> create a single numeric element that can be placed its respective slot in a >> 64-element list, named "list1". For example, mat1[11,1:5] = 0,1,1,0,1 and I >> must put 01101, with a length of 1, into the 11th element of list1. I can >> create the code for an iterative process, but am having a great deal of >> difficulty in figuring out how to create a single element from the row >> values, especially when the first value is 0, as in my example. >> >> >> Thanks in advance. >> >>[[alternative HTML version deleted]] >> >> __ >> R-help@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. >> > > [[alternative HTML version deleted]] __ R-help@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.
[R] matrix rows to single numeric element
I have a matrix of 5 columns and 64 rows, let's call it "mat1". All values are 1 or 0. I need to take the values of the elements by row and create a single numeric element that can be placed its respective slot in a 64-element list, named "list1". For example, mat1[11,1:5] = 0,1,1,0,1 and I must put 01101, with a length of 1, into the 11th element of list1. I can create the code for an iterative process, but am having a great deal of difficulty in figuring out how to create a single element from the row values, especially when the first value is 0, as in my example. Thanks in advance. [[alternative HTML version deleted]] __ R-help@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.
[R] matrix indexing (igraph ?)
I realize that matrix indexing has been addressed in various flavors, but I'm stumped and didn't find anything in the archives. It's not clear if it is an igraph issue or a more general problem. Thanks in advance for your patience. I am using igraph to read a gml file (http://www-personal.umich.edu/~mejn/netdata/football.zip ). The gml file contains vertex attributes (conference and team) that are provided as character/integer values. I would like to build a matrix of dimension (length.team, length.conference) where the elements are zero except for 1's at the location of index [team, conference]. Here is a snippet of code that hopefully captures what I am trying to do: original<-read.graph("./Data/football/football.gml", format="gml") conf.list<- get.vertex.attribute(original, 'value', index=V(original))+1 team.list<- get.vertex.attribute(original, 'id', index=V(original))+1 temp<- matrix(0,115,12) temp[team.list, conf.list]<-1 Unfortunately, temp[] is filled with 1's. However, if I try: c.list=c(1,3,5) t.list=c(2,4,6) temp[t.list,c.list]<-1 then things work as I would expect. FWIW - I have tried as.integer(get.vertex.attribute(...)) with no luck. Thanks for any suggestions. * > original<-read.graph("./Data/football/football.gml", format="gml") > conf.list<- get.vertex.attribute(original, 'value', index=V(original))+1 > team.list<- get.vertex.attribute(original, 'id', index=V(original))+1 > conf.list [1] 8 1 3 4 8 4 3 9 9 8 4 11 7 3 7 3 8 10 7 2 10 9 9 8 11 1 7 10 12 2 2 7 3 1 7 2 6 [38] 1 7 3 4 8 6 7 5 1 12 3 5 12 11 9 4 12 7 2 10 5 12 11 3 7 10 11 3 10 5 12 9 11 10 7 4 12 [75] 4 5 10 9 9 2 6 4 6 12 4 7 5 10 12 1 6 5 5 8 2 10 10 11 4 7 3 2 4 1 8 1 3 4 9 1 5 [112] 9 5 10 12 > team.list [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 [82] 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 [109] 109 110 111 112 113 114 115 > length(conf.list) [1] 115 > length(team.list) [1] 115 > temp<- matrix(0,115,12) > r<-c(1,3,5) > col<- c(2,4,6) > temp[r,col]<-1 > temp[1:10,] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,]010101000 0 0 0 [2,]000000000 0 0 0 [3,]010101000 0 0 0 [4,]000000000 0 0 0 [5,]010101000 0 0 0 [6,]000000000 0 0 0 [7,]000000000 0 0 0 [8,]000000000 0 0 0 [9,]000000000 0 0 0 [10,]000000000 0 0 0 > temp[team.list,conf.list]<- 1 > temp[1:10,] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,]111111111 1 1 1 [2,]111111111 1 1 1 [3,]111111111 1 1 1 [4,]111111111 1 1 1 [5,]111111111 1 1 1 [6,]111111111 1 1 1 [7,]111111111 1 1 1 [8,]111111111 1 1 1 [9,]111111111 1 1 1 [10,]111111111 1 1 1 > > - [[alternative HTML version deleted]] __ R-help@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.
[R] Matrix operation with apply family functions
Dear all, I am trying to use the apply family functions to improve the efficiency of my code, though it is a bit hard for me to find sometimes the solutions with these functions. The problem that I want to solve is: I have a matrix of replicated random generated data, e.g. if I have two controls with 100 observations and replicated the data 100 times then I am going to have a 100x2000 matrix (odd rows have the control x1 and even rows control x2). Then I want to multiply a vector of order two in this example (q in general) by each observation of the random generated data, so at the end I am going to obtain a 100x1000 matrix. A solution to the above problem is given by the following code without using apply family functions and is efficient I think as well, but I would like to know if there is another way because I think the other way can solve similar problems that I have and this particular way cannot solve. x.1<-replicate(1000, rnorm(100,0,1)) x.2<-replicate(1000, rnorm(100,1,1)) Z<-BETA[1,]*x.1+BETA[2,]*x.2 Potential set up of the problem I want to solve with the apply family functions: X<-replicate(1000, c(rnorm(n,0,1), rnorm(n,1,1))) X<-matrix(X, nrow=100, ncol=2000) Z<-apply(X, ...???..)or even better another family apply function Thank you Dimitris -- View this message in context: http://r.789695.n4.nabble.com/Matrix-operation-with-apply-family-functions-tp3660702p3660702.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] Matrix 3d plot
On Jul 5, 2011, at 1:36 PM, петрович wrote: I have a problem with a 3d plot, suppose we have a matrix like this: v1v2 v3 v4 jan-2010 0.5 0.250.250.3 feb-2010 0.35 0.12 0.120.4 mar-20100.150.250.25 0.1 and i want to plot this matrix in 3d plot where x-axis is the first column of the matrix above, y - axis is the first row of the matrix above and the z-axis is the numbers corresponding, so z(jan-2010,v3)=0.25 I was trying with persp() But you didn't show your code. but i see that in this function z is a vector That is not how I read help(persp). but in my case is a matrix, Assuming the matrix is named "z", what happens with : persp(z=z) so i receive an error message And after reading the Posting Guide you will see that you are asked to report any error message verbatim. And perhaps even more importantly it asks that you provide a reproducible version of your object with dump. It's even easier to use dput, but do include one or the other. I think this sound no so hard, but actually i couldn´t find a function doing this, is there actually such a function? There are many. But why not see if you can get persp to work? Christian __ R-help@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. David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] Matrix 3d plot
On 05/07/2011 1:36 PM, петрович wrote: I have a problem with a 3d plot, suppose we have a matrix like this: v1v2 v3 v4 jan-2010 0.5 0.250.250.3 feb-2010 0.35 0.12 0.120.4 mar-20100.150.250.25 0.1 and i want to plot this matrix in 3d plot where x-axis is the first column of the matrix above, y - axis is the first row of the matrix above and the z-axis is the numbers corresponding, so z(jan-2010,v3)=0.25 I was trying with persp() but i see that in this function z is a vector but in my case is a matrix, so i receive an error message I think this sound no so hard, but actually i couldn´t find a function doing this, is there actually such a function? persp() handles exactly the case you describe, but it wants numeric x and y. You didn't show what you tried, but this works: x <- 1:3 y <- 1:4 z <- matrix(rnorm(12), nrow=3) persp(x,y,z, col="red") It's not a very useful plot with the random data; it might be better with yours. Duncan Murdoch __ R-help@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.
[R] Matrix 3d plot
I have a problem with a 3d plot, suppose we have a matrix like this: v1v2 v3 v4 jan-2010 0.5 0.250.250.3 feb-2010 0.35 0.12 0.120.4 mar-20100.150.250.25 0.1 and i want to plot this matrix in 3d plot where x-axis is the first column of the matrix above, y - axis is the first row of the matrix above and the z-axis is the numbers corresponding, so z(jan-2010,v3)=0.25 I was trying with persp() but i see that in this function z is a vector but in my case is a matrix, so i receive an error message I think this sound no so hard, but actually i couldn´t find a function doing this, is there actually such a function? Christian __ R-help@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.
[R] matrix problem-replacing pieces of a matrix
#Hallo again.. Thank you for your answers. To sum up: #The problem was that we have the matrix m m<-matrix(numeric(length=5*4),nrow=5,ncol=4) m # [,1] [,2] [,3] [,4] # [1,]0000 # [2,]0000 # [3,]0000 # [4,]0000 # [5,]0000 #and a vector y y<-c(1,1,1,3,3) #y has informations about the rows of m, #and we wanted to change the rows that correspond to y==1 #with the vector c(1,2,3,4). The most intuitive procedure didn't work m[y==1,1:4]<-c(1,2,3,4) m # [,1] [,2] [,3] [,4] # [1,]1432 # [2,]2143 # [3,]3214 # [4,]0000 # [5,]0000 #because the matrix is being filled by column. The second thought was to #work with the transpose matrix. m_temp<-t(m) m_temp[1:4,y==1]<-c(1,2,3,4) m<-t(m_temp) #R assigns to an object another object of the same class. So the other way proposed #by Sara is to to assign to the submatrix m[y==1,] #of m another matrix matrix(1:4,nrow=sum(y==1),ncol=ncol(m),byrow=T) #That is: m[y==1,]<-matrix(1:4,nrow=sum(y==1),ncol(m),byrow=T) m # [,1] [,2] [,3] [,4] # [1,]1234 # [2,]1234 # [3,]1234 # [4,]0000 # [5,]0000 #The last way to do this was proposed by David, Patric and it is discussed #in Circle 8 (8.3.25--replacing pieces of a matrix) of R-inferno book. m[y==1,1:4]<-rep(c(1,2,3,4),each=sum(y==1)) __ R-help@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.
Re: [R] matrix problem
On Jun 20, 2011, at 3:54 PM, Costis Ghionnis wrote: Hallo everyone! I have a problem about creating a matrix... Suppose we have a vector y<-c(1,1,1,3,2) and a zero matrix, m ,with nrows=length(y) and ncol=4. The matrix would look like this: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I want to change the first three rows with the vector c(1,2,3,4). I thought that with the command m[y==1,1:4]<-c(1,2,3,4) i would get 1 2 3 4 1 2 3 4 1 2 3 4 0 0 0 0 0 0 0 0 Try: > m[y==1,1:4]<-rep( c(1,2,3,4), each= sum(y==1) ) > m [,1] [,2] [,3] [,4] [1,]1234 [2,]1234 [3,]1234 [4,]0000 [5,]0000 -- David. but instead i am getting 1 4 3 2 2 1 4 3 3 2 1 4 0 0 0 0 0 0 0 0 It seems it is filling the data by col instead by row. I want to use this technique in more complicated problems. So i do not want to have to work with the transpose matrix. Do you know another way to make this work. Thank you... __ R-help@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. David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] matrix problem
How about: y <- c(1,1,1,3,2) m <- matrix(0, nrow=length(y), ncol=4) m[y==1, ] <- matrix(1:4, nrow=sum(y == 1), ncol=4, byrow=TRUE) or, depending on your actual problem y <- c(1,1,1,3,2) m <- matrix(0, nrow=length(y), ncol=4) m[y == 1,] <- col(m[y == 1,]) Sarah On Mon, Jun 20, 2011 at 3:54 PM, Costis Ghionnis wrote: > Hallo everyone! I have a problem about creating a matrix... > > Suppose we have a vector y<-c(1,1,1,3,2) > > and a zero matrix, m ,with nrows=length(y) and ncol=4. > > The matrix would look like this: > 0 0 0 0 > 0 0 0 0 > 0 0 0 0 > 0 0 0 0 > 0 0 0 0 > > I want to change the first three rows with the vector c(1,2,3,4). > I thought that with the command m[y==1,1:4]<-c(1,2,3,4) i would get > > 1 2 3 4 > 1 2 3 4 > 1 2 3 4 > 0 0 0 0 > 0 0 0 0 > > but instead i am getting > > 1 4 3 2 > 2 1 4 3 > 3 2 1 4 > 0 0 0 0 > 0 0 0 0 > > It seems it is filling the data by col instead by row. I want to use this > technique in more complicated problems. > So i do not want to have to work with the transpose matrix. Do you know > another way to make this work. Thank you... > -- Sarah Goslee http://www.functionaldiversity.org __ R-help@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.
[R] matrix problem
Hallo everyone! I have a problem about creating a matrix... Suppose we have a vector y<-c(1,1,1,3,2) and a zero matrix, m ,with nrows=length(y) and ncol=4. The matrix would look like this: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I want to change the first three rows with the vector c(1,2,3,4). I thought that with the command m[y==1,1:4]<-c(1,2,3,4) i would get 1 2 3 4 1 2 3 4 1 2 3 4 0 0 0 0 0 0 0 0 but instead i am getting 1 4 3 2 2 1 4 3 3 2 1 4 0 0 0 0 0 0 0 0 It seems it is filling the data by col instead by row. I want to use this technique in more complicated problems. So i do not want to have to work with the transpose matrix. Do you know another way to make this work. Thank you... __ R-help@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.
Re: [R] Matrix Question
Here is one way you might do it. > con <- textConnection(" + characteristics_ch1.3 Stage: T1N0 Stage: T2N1 + Stage: T0N0 Stage: T1N0 Stage: T0N3 + ") > txt <- scan(con, what = "") Read 11 items > close(con) > > Ts <- grep("^T", txt, value = TRUE) > Ts <- sub("T([[:digit:]]+)N([[:digit:]]+)", "\\1x\\2", Ts) > out <- do.call(rbind, strsplit(Ts, "x")) > mode(out) <- "numeric" > dimnames(out) <- list(rep("", nrow(out)), c("T", "N")) > > out T N 1 0 2 1 0 0 1 0 0 3 > Now you can print 'out' however you want it, e.g. > sink("outfile.txt") > out > sink() This is slightly more complex than it might be as I have allowed for the possibility that your numbers have more than one digit. Bill Venables. -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Ben Ganzfried Sent: Friday, 3 June 2011 4:54 AM To: r-help@r-project.org Subject: [R] Matrix Question Hi, First of all, I would like to introduce myself as I will probably have many questions over the next few weeks and want to thank you guys in advance for your help. I'm a cancer researcher and I need to learn R to complete a few projects. I have an introductory background in Python. My questions at the moment are based on the following sample input file: *Sample_Input_File* characteristics_ch1.3 Stage: T1N0 Stage: T2N1 Stage: T0N0 Stage: T1N0 Stage: T0N3 "characteristics_ch1.3" is a column header in the input excel file. "T's" represent stage and "N's" represent degree of disease spreading. I want to create output that looks like this: *Sample_Output_File* T N 1 0 2 1 0 0 1 0 0 3 As it currently stands, my code is the following: rm(list=ls()) source("../../functions.R") uncurated <- read.csv("../uncurated/Sample_Input_File_full_pdata.csv",as.is =TRUE,row.names=1) ##initial creation of curated dataframe curated <- initialCuratedDF(rownames(uncurated),template.filename="Sample_Template_File.csv") ## ##start the mappings ## ##title -> alt_sample_name curated$alt_sample_name <- uncurated$title #T tmp <- uncurated$characteristics_ch1.3 tmp <- *??* curated$T <- tmp #N tmp <- uncurated$characteristics_ch1.3 tmp <- *??* curated$N <- tmp write.table(curated, row.names=FALSE, file="../curated/Sample_Output_File_curated_pdata.txt",sep="\t") My question is the following: What code gets me the desired output (replacing the *??*'s above)? I want to: a) Find the integer value one element to the right of "T"; and b) find the integer value one element to the right of "N". I've read the regular expression tutorial for R, but could only figure out how to grab an integer value if it is the only integer value in the row (ie more than one integer value makes this basic regular expression unsuccessful). Thank you very much for any help you can provide. Sincerely, Ben Ganzfried [[alternative HTML version deleted]] __ R-help@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. __ R-help@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.
[R] Matrix Question
Hi, First of all, I would like to introduce myself as I will probably have many questions over the next few weeks and want to thank you guys in advance for your help. I'm a cancer researcher and I need to learn R to complete a few projects. I have an introductory background in Python. My questions at the moment are based on the following sample input file: *Sample_Input_File* characteristics_ch1.3 Stage: T1N0 Stage: T2N1 Stage: T0N0 Stage: T1N0 Stage: T0N3 "characteristics_ch1.3" is a column header in the input excel file. "T's" represent stage and "N's" represent degree of disease spreading. I want to create output that looks like this: *Sample_Output_File* T N 1 0 2 1 0 0 1 0 0 3 As it currently stands, my code is the following: rm(list=ls()) source("../../functions.R") uncurated <- read.csv("../uncurated/Sample_Input_File_full_pdata.csv",as.is =TRUE,row.names=1) ##initial creation of curated dataframe curated <- initialCuratedDF(rownames(uncurated),template.filename="Sample_Template_File.csv") ## ##start the mappings ## ##title -> alt_sample_name curated$alt_sample_name <- uncurated$title #T tmp <- uncurated$characteristics_ch1.3 tmp <- *??* curated$T <- tmp #N tmp <- uncurated$characteristics_ch1.3 tmp <- *??* curated$N <- tmp write.table(curated, row.names=FALSE, file="../curated/Sample_Output_File_curated_pdata.txt",sep="\t") My question is the following: What code gets me the desired output (replacing the *??*'s above)? I want to: a) Find the integer value one element to the right of "T"; and b) find the integer value one element to the right of "N". I've read the regular expression tutorial for R, but could only figure out how to grab an integer value if it is the only integer value in the row (ie more than one integer value makes this basic regular expression unsuccessful). Thank you very much for any help you can provide. Sincerely, Ben Ganzfried [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix not working
Please... ?"[" Online tutorial "An Introduction to R." I think you'll find everything you need in these. -- Bert On Thu, May 26, 2011 at 12:39 PM, Dat Mai wrote: > When I use the as.matrix, the data.frame does turn into a matrix, but I > cannot change the dimensions of the matrix. I'd still want it to have that > pseudo cartesian format (e.g. [a1,b1], [a2,b2]) > > On Thu, May 26, 2011 at 6:58 PM, David Winsemius > wrote: > >> >> On May 26, 2011, at 1:53 PM, Andy Zhu wrote: >> >> Dat: >>> >>> 1. you can use as.matrix to convert data.frame to matrix; >>> 2. it is likely that the internal representation of your data.frame may >>> not be numerical value; matrix can only take on numeric. >>> >>> >> Not true. Can be any single mode, including "character", "list", and >> "logical". >> >> -- >> david. >> >> >> >>> >>> --- On Thu, 5/26/11, Dat Mai wrote: >>> >>> From: Dat Mai >>> Subject: [R] matrix not working >>> To: r-help@r-project.org >>> Date: Thursday, May 26, 2011, 12:24 PM >>> >>> Hello All, >>> >>> I'm trying to create a matrix from a dataframe (let's call it df): >>> ..a..b.c.d >>> a inputs output >>> b inputs output >>> c inputs output >>> d inputs output >>> e inputs output >>> >>> The inputs are represented by columns a and b >>> The outputs are represented by columns c and d, but the only outputs are >>> those from column d >>> - some values from column d are NA >>> - column d was created with the code: >>> >>> df$d=rank(df$c, na.last="keep") >>> >>> #--R Code-# >>> item=unique(df$a) >>> n=length(list) >>> >>> r=matrix(data=NA,nrow=n, ncol=n, dimnames=list(PRR1=item, PRR2=item)) >>> >>> for(j in 2:ln) >>> { >>> for(i in 1:(j-1)) >>> { >>> input1=rownames(r)[i] >>> input2=colnames(r)[j] >>> >>> q=df[(df$a==input1 & df$b==input2), "d"] >>> >>> if(length(q)==0) >>> { >>> q=df[(df$a==input2 & df$b==input1), "d"] >>> } >>> >>> if(length(q)==0) >>> { >>> q=NA >>> } >>> >>> r[j,i]=q >>> r[i,j]=q >>> r[j,j]=q >>> } >>> } >>> >>> The result is a matrix with the appropriate dimensions, but everything is >>> filled with NA instead of the rankings of the various combinations. I'd >>> like >>> for the matrix to be filled with the ranking values--what have I done >>> wrong? >>> -- >>> Best, >>> Dat Mai >>> PhD Rotation Student >>> Albert Einstein College of Medicine >>> >>> [[alternative HTML version deleted]] >>> >>> __ >>> R-help@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. >>> >>> [[alternative HTML version deleted]] >>> >>> __ >>> R-help@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. >>> >> >> David Winsemius, MD >> West Hartford, CT >> >> > > > -- > Best, > Dat Mai > PhD Rotation Student > Albert Einstein College of Medicine > > [[alternative HTML version deleted]] > > __ > R-help@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. > -- "Men by nature long to get on to the ultimate truths, and will often be impatient with elementary studies or fight shy of them. If it were possible to reach the ultimate truths without the elementary studies usually prefixed to them, these would not be preparatory studies but superfluous diversions." -- Maimonides (1135-1204) Bert Gunter Genentech Nonclinical Biostatistics __ R-help@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.
Re: [R] matrix not working
When I use the as.matrix, the data.frame does turn into a matrix, but I cannot change the dimensions of the matrix. I'd still want it to have that pseudo cartesian format (e.g. [a1,b1], [a2,b2]) On Thu, May 26, 2011 at 6:58 PM, David Winsemius wrote: > > On May 26, 2011, at 1:53 PM, Andy Zhu wrote: > > Dat: >> >> 1. you can use as.matrix to convert data.frame to matrix; >> 2. it is likely that the internal representation of your data.frame may >> not be numerical value; matrix can only take on numeric. >> >> > Not true. Can be any single mode, including "character", "list", and > "logical". > > -- > david. > > > >> >> --- On Thu, 5/26/11, Dat Mai wrote: >> >> From: Dat Mai >> Subject: [R] matrix not working >> To: r-help@r-project.org >> Date: Thursday, May 26, 2011, 12:24 PM >> >> Hello All, >> >> I'm trying to create a matrix from a dataframe (let's call it df): >> ..a..b.c.d >> a inputs output >> b inputs output >> c inputs output >> d inputs output >> e inputs output >> >> The inputs are represented by columns a and b >> The outputs are represented by columns c and d, but the only outputs are >> those from column d >> - some values from column d are NA >> - column d was created with the code: >> >> df$d=rank(df$c, na.last="keep") >> >> #--R Code-# >> item=unique(df$a) >> n=length(list) >> >> r=matrix(data=NA,nrow=n, ncol=n, dimnames=list(PRR1=item, PRR2=item)) >> >> for(j in 2:ln) >> { >> for(i in 1:(j-1)) >> { >>input1=rownames(r)[i] >>input2=colnames(r)[j] >> >>q=df[(df$a==input1 & df$b==input2), "d"] >> >>if(length(q)==0) >>{ >> q=df[(df$a==input2 & df$b==input1), "d"] >>} >> >>if(length(q)==0) >>{ >> q=NA >>} >> >>r[j,i]=q >>r[i,j]=q >>r[j,j]=q >> } >> } >> >> The result is a matrix with the appropriate dimensions, but everything is >> filled with NA instead of the rankings of the various combinations. I'd >> like >> for the matrix to be filled with the ranking values--what have I done >> wrong? >> -- >> Best, >> Dat Mai >> PhD Rotation Student >> Albert Einstein College of Medicine >> >>[[alternative HTML version deleted]] >> >> __ >> R-help@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. >> >>[[alternative HTML version deleted]] >> >> __ >> R-help@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. >> > > David Winsemius, MD > West Hartford, CT > > -- Best, Dat Mai PhD Rotation Student Albert Einstein College of Medicine [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix not working
On May 26, 2011, at 1:53 PM, Andy Zhu wrote: Dat: 1. you can use as.matrix to convert data.frame to matrix; 2. it is likely that the internal representation of your data.frame may not be numerical value; matrix can only take on numeric. Not true. Can be any single mode, including "character", "list", and "logical". -- david. --- On Thu, 5/26/11, Dat Mai wrote: From: Dat Mai Subject: [R] matrix not working To: r-help@r-project.org Date: Thursday, May 26, 2011, 12:24 PM Hello All, I'm trying to create a matrix from a dataframe (let's call it df): ..a..b.c.d a inputs output b inputs output c inputs output d inputs output e inputs output The inputs are represented by columns a and b The outputs are represented by columns c and d, but the only outputs are those from column d - some values from column d are NA - column d was created with the code: df$d=rank(df$c, na.last="keep") #--R Code-----# item=unique(df$a) n=length(list) r=matrix(data=NA,nrow=n, ncol=n, dimnames=list(PRR1=item, PRR2=item)) for(j in 2:ln) { for(i in 1:(j-1)) { input1=rownames(r)[i] input2=colnames(r)[j] q=df[(df$a==input1 & df$b==input2), "d"] if(length(q)==0) { q=df[(df$a==input2 & df$b==input1), "d"] } if(length(q)==0) { q=NA } r[j,i]=q r[i,j]=q r[j,j]=q } } The result is a matrix with the appropriate dimensions, but everything is filled with NA instead of the rankings of the various combinations. I'd like for the matrix to be filled with the ranking values--what have I done wrong? -- Best, Dat Mai PhD Rotation Student Albert Einstein College of Medicine [[alternative HTML version deleted]] __ R-help@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. [[alternative HTML version deleted]] __ R-help@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. David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] matrix not working
Dat: 1. you can use as.matrix to convert data.frame to matrix; 2. it is likely that the internal representation of your data.frame may not be numerical value; matrix can only take on numeric. --- On Thu, 5/26/11, Dat Mai wrote: From: Dat Mai Subject: [R] matrix not working To: r-help@r-project.org Date: Thursday, May 26, 2011, 12:24 PM Hello All, I'm trying to create a matrix from a dataframe (let's call it df): ..a..b.c.d a inputs output b inputs output c inputs output d inputs output e inputs output The inputs are represented by columns a and b The outputs are represented by columns c and d, but the only outputs are those from column d - some values from column d are NA - column d was created with the code: df$d=rank(df$c, na.last="keep") #--R Code-# item=unique(df$a) n=length(list) r=matrix(data=NA,nrow=n, ncol=n, dimnames=list(PRR1=item, PRR2=item)) for(j in 2:ln) { for(i in 1:(j-1)) { input1=rownames(r)[i] input2=colnames(r)[j] q=df[(df$a==input1 & df$b==input2), "d"] if(length(q)==0) { q=df[(df$a==input2 & df$b==input1), "d"] } if(length(q)==0) { q=NA } r[j,i]=q r[i,j]=q r[j,j]=q } } The result is a matrix with the appropriate dimensions, but everything is filled with NA instead of the rankings of the various combinations. I'd like for the matrix to be filled with the ranking values--what have I done wrong? -- Best, Dat Mai PhD Rotation Student Albert Einstein College of Medicine [[alternative HTML version deleted]] __ R-help@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. [[alternative HTML version deleted]] __ R-help@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.
[R] matrix not working
Hello All, I'm trying to create a matrix from a dataframe (let's call it df): ..a..b.c.d a inputs output b inputs output c inputs output d inputs output e inputs output The inputs are represented by columns a and b The outputs are represented by columns c and d, but the only outputs are those from column d - some values from column d are NA - column d was created with the code: df$d=rank(df$c, na.last="keep") #--R Code-# item=unique(df$a) n=length(list) r=matrix(data=NA,nrow=n, ncol=n, dimnames=list(PRR1=item, PRR2=item)) for(j in 2:ln) { for(i in 1:(j-1)) { input1=rownames(r)[i] input2=colnames(r)[j] q=df[(df$a==input1 & df$b==input2), "d"] if(length(q)==0) { q=df[(df$a==input2 & df$b==input1), "d"] } if(length(q)==0) { q=NA } r[j,i]=q r[i,j]=q r[j,j]=q } } The result is a matrix with the appropriate dimensions, but everything is filled with NA instead of the rankings of the various combinations. I'd like for the matrix to be filled with the ranking values--what have I done wrong? -- Best, Dat Mai PhD Rotation Student Albert Einstein College of Medicine [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix Manipulation...
It's very easy to do in two steps: > testmat <- matrix(c(.2, .3, 1, -1, 3, .2, .4, 5, .5, -1), byrow=TRUE, nrow=2) > testmat [,1] [,2] [,3] [,4] [,5] [1,] 0.2 0.31 -1.03 [2,] 0.2 0.45 0.5 -1 > testmat[testmat >= 1] <- 1 > testmat[testmat < 0] <- 0 > testmat [,1] [,2] [,3] [,4] [,5] [1,] 0.2 0.31 0.01 [2,] 0.2 0.41 0.50 This is pretty basic. You might want to read one of the many excellent intro to R guides, especially the subsetting section. Sarah On Wed, May 25, 2011 at 2:51 PM, Jim Silverton wrote: > Hello everyone, > > > I have a 2 x 5 matrix: say > > 0.2 0.3 1 -1 3 > 0.2. 0.4 5 0.5 -1 > > I want to replace all the values greater than or equal to 1 with 1 and those > less than or equal to 0 with 0. So I should end up with a mtrix looking > like: > > 0.2 0.3 1 0 1 > 0.2. 0.4 1 0.5 0 > > Any ideas how to do this? > > -- > Thanks, > Jim. -- Sarah Goslee http://www.functionaldiversity.org __ R-help@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.
Re: [R] matrix Manipulation...
Hello everyone, I have a 2 x 5 matrix: say 0.2 0.3 1 -1 3 0.2. 0.4 5 0.5 -1 I want to replace all the values greater than or equal to 1 with 1 and those less than or equal to 0 with 0. So I should end up with a mtrix looking like: 0.2 0.3 1 0 1 0.2. 0.4 1 0.5 0 Any ideas how to do this? -- Thanks, Jim. [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix help (first occurrence of variable in column)
Is this what you are looking for: > mdat3 sp.1 sp.2 sp.3 sp.4 sp.5 T110010 T210010 T311100 T410111 > > # create a matrix of when species first appeared > first <- apply(mdat3, 2, function(x) (cumsum(x == 1) > 0) + 0L) > # use first row as the number of starting species > start <- sum(first[1,]) > # add column of new species; need diff to see growth > mdat3 <- cbind(mdat3, new = c(0, diff(rowSums(first) - start))) > > mdat3 sp.1 sp.2 sp.3 sp.4 sp.5 new T110010 0 T210010 0 T311100 2 T410111 1 > > On Thu, May 19, 2011 at 9:46 AM, Michael Denslow wrote: > On Wed, May 18, 2011 at 9:49 PM, jim holtman wrote: >> Is this what you were after: >> >>> mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, >> + dimnames = list(c("T1", "T2"), >> + c("sp.1", "sp.2", "sp.3"))) >>> >>> mdat >> sp.1 sp.2 sp.3 >> T1 1 0 1 >> T2 1 1 0 >>> # do 'rle' on each column and see if it is length >1 and starts with zero >>> mdat.df <- as.data.frame(mdat) >>> new.spec <- sapply(mdat.df, function(x){ >> + x.rle <- rle(x) >> + (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) >> + }) >>> names(mdat.df)[new.spec] >> [1] "sp.2" >>> > > Thanks for your reply! > This is close to what I want, but I think it only works if there is > two rows. My actual data could have up to 8 rows (time samples). > > An example with 4 rows: > > mdat3 <- matrix(c(1,0,0,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1), nrow = 4, > ncol=5, byrow=TRUE, > dimnames = list(c("T1", "T2",'T3','T4'), > c("sp.1", "sp.2", "sp.3","sp.4","sp.5"))) > > mdat3 > > mdat.df <- as.data.frame(mdat3) > new.spec <- sapply(mdat.df, function(x){ > x.rle <- rle(x) > (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) > }) > > names(mdat.df)[new.spec] > > It should say sp.5 since all the other species have occurred in other > samples. Any further help would be much appreciated. > > >> >> On Wed, May 18, 2011 at 9:37 AM, Michael Denslow >> wrote: >>> Dear R help, >>> Apologies for the less than informative subject line. I will do my >>> best to describe my problem. >>> >>> Consider the following matrix: >>> >>> mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, >>> dimnames = list(c("T1", "T2"), >>> c("sp.1", "sp.2", "sp.3"))) >>> >>> mdat >>> >>> In my actual data I have time (rows) and species occurrences (0/1 >>> values, columns). I want to count the number of new species that occur >>> at a given time sample. For the matrix above the answer would be 1. >>> >>> Is there a simple way to figure out if the species has never occurred >>> before and then sum them up? >>> >>> Thanks in advance, >>> Micheal >>> >>> -- >>> Michael Denslow >>> >>> I.W. Carpenter Jr. Herbarium [BOON] >>> Department of Biology >>> Appalachian State University >>> Boone, North Carolina U.S.A. >>> -- AND -- >>> Communications Manager >>> Southeast Regional Network of Expertise and Collections >>> sernec.org >>> >>> 36.214177, -81.681480 +/- 3103 meters >>> >>> __ >>> R-help@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. >>> >> >> >> >> -- >> Jim Holtman >> Data Munger Guru >> >> What is the problem that you are trying to solve? >> > > > > -- > Michael Denslow > > I.W. Carpenter Jr. Herbarium [BOON] > Department of Biology > Appalachian State University > Boone, North Carolina U.S.A. > -- AND -- > Communications Manager > Southeast Regional Network of Expertise and Collections > sernec.org > > 36.214177, -81.681480 +/- 3103 meters > -- Jim Holtman Data Munger Guru What is the problem that you are trying to solve? __ R-help@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.
Re: [R] matrix help (first occurrence of variable in column)
On Wed, May 18, 2011 at 9:49 PM, jim holtman wrote: > Is this what you were after: > >> mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, > + dimnames = list(c("T1", "T2"), > + c("sp.1", "sp.2", "sp.3"))) >> >> mdat > sp.1 sp.2 sp.3 > T1 1 0 1 > T2 1 1 0 >> # do 'rle' on each column and see if it is length >1 and starts with zero >> mdat.df <- as.data.frame(mdat) >> new.spec <- sapply(mdat.df, function(x){ > + x.rle <- rle(x) > + (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) > + }) >> names(mdat.df)[new.spec] > [1] "sp.2" >> Thanks for your reply! This is close to what I want, but I think it only works if there is two rows. My actual data could have up to 8 rows (time samples). An example with 4 rows: mdat3 <- matrix(c(1,0,0,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1), nrow = 4, ncol=5, byrow=TRUE, dimnames = list(c("T1", "T2",'T3','T4'), c("sp.1", "sp.2", "sp.3","sp.4","sp.5"))) mdat3 mdat.df <- as.data.frame(mdat3) new.spec <- sapply(mdat.df, function(x){ x.rle <- rle(x) (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) }) names(mdat.df)[new.spec] It should say sp.5 since all the other species have occurred in other samples. Any further help would be much appreciated. > > On Wed, May 18, 2011 at 9:37 AM, Michael Denslow > wrote: >> Dear R help, >> Apologies for the less than informative subject line. I will do my >> best to describe my problem. >> >> Consider the following matrix: >> >> mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, >> dimnames = list(c("T1", "T2"), >> c("sp.1", "sp.2", "sp.3"))) >> >> mdat >> >> In my actual data I have time (rows) and species occurrences (0/1 >> values, columns). I want to count the number of new species that occur >> at a given time sample. For the matrix above the answer would be 1. >> >> Is there a simple way to figure out if the species has never occurred >> before and then sum them up? >> >> Thanks in advance, >> Micheal >> >> -- >> Michael Denslow >> >> I.W. Carpenter Jr. Herbarium [BOON] >> Department of Biology >> Appalachian State University >> Boone, North Carolina U.S.A. >> -- AND -- >> Communications Manager >> Southeast Regional Network of Expertise and Collections >> sernec.org >> >> 36.214177, -81.681480 +/- 3103 meters >> >> __ >> R-help@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. >> > > > > -- > Jim Holtman > Data Munger Guru > > What is the problem that you are trying to solve? > -- Michael Denslow I.W. Carpenter Jr. Herbarium [BOON] Department of Biology Appalachian State University Boone, North Carolina U.S.A. -- AND -- Communications Manager Southeast Regional Network of Expertise and Collections sernec.org 36.214177, -81.681480 +/- 3103 meters __ R-help@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.
Re: [R] matrix help (first occurrence of variable in column)
Is this what you were after: > mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, + dimnames = list(c("T1", "T2"), + c("sp.1", "sp.2", "sp.3"))) > > mdat sp.1 sp.2 sp.3 T1101 T2110 > # do 'rle' on each column and see if it is length >1 and starts with zero > mdat.df <- as.data.frame(mdat) > new.spec <- sapply(mdat.df, function(x){ + x.rle <- rle(x) + (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) + }) > names(mdat.df)[new.spec] [1] "sp.2" > On Wed, May 18, 2011 at 9:37 AM, Michael Denslow wrote: > Dear R help, > Apologies for the less than informative subject line. I will do my > best to describe my problem. > > Consider the following matrix: > > mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, > dimnames = list(c("T1", "T2"), > c("sp.1", "sp.2", "sp.3"))) > > mdat > > In my actual data I have time (rows) and species occurrences (0/1 > values, columns). I want to count the number of new species that occur > at a given time sample. For the matrix above the answer would be 1. > > Is there a simple way to figure out if the species has never occurred > before and then sum them up? > > Thanks in advance, > Micheal > > -- > Michael Denslow > > I.W. Carpenter Jr. Herbarium [BOON] > Department of Biology > Appalachian State University > Boone, North Carolina U.S.A. > -- AND -- > Communications Manager > Southeast Regional Network of Expertise and Collections > sernec.org > > 36.214177, -81.681480 +/- 3103 meters > > __ > R-help@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. > -- Jim Holtman Data Munger Guru What is the problem that you are trying to solve? __ R-help@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.
[R] matrix help (first occurrence of variable in column)
Dear R help, Apologies for the less than informative subject line. I will do my best to describe my problem. Consider the following matrix: mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, dimnames = list(c("T1", "T2"), c("sp.1", "sp.2", "sp.3"))) mdat In my actual data I have time (rows) and species occurrences (0/1 values, columns). I want to count the number of new species that occur at a given time sample. For the matrix above the answer would be 1. Is there a simple way to figure out if the species has never occurred before and then sum them up? Thanks in advance, Micheal -- Michael Denslow I.W. Carpenter Jr. Herbarium [BOON] Department of Biology Appalachian State University Boone, North Carolina U.S.A. -- AND -- Communications Manager Southeast Regional Network of Expertise and Collections sernec.org 36.214177, -81.681480 +/- 3103 meters __ R-help@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.
Re: [R] Matrix manipulation in for loop
hello I think if you try this: for(j in 1: length(nsample)){ MEANS[,]<-create.means.one.size(j,var,nboot) } it will work -- View this message in context: http://r.789695.n4.nabble.com/Matrix-manipulation-in-for-loop-tp3525849p3525888.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
[R] Matrix manipulation in for loop
Hi all, I have a problem with getting my code to do what I want! This is the code I have: create.means.one.size<-function(nsample,var,nboot){ mat.x<-matrix(0,nrow=nboot,ncol=nsample) for(i in 1:nboot){ mat.x[i,]<-sample(var,nsample,replace=T) } mean.mat<-rep(0,nboot) for(i in 1:nboot){ mean.mat[i]<-mean(mat.x[i,]) } sd.mean<-sd(mean.mat) return(mean.mat) } where nsample here is a scalar. Then this is where I have the problem create.all.means<-function(nsample,var,nboot){ MEANS<-matrix(0,nrow=nboot,ncol=length(nsample)) for(j in nsample){ MEANS[,]<-create.means.one.size(j,var,nboot) } return(A=list("MEANS"=MEANS,"nsample"=nsample,"std.dev"=sd(MEANS))) } here nsample is a vector of the different sample sizes I want. This function should first create an empty matrix MEANS then it loops through the possible values of nsample each time it calls create means.one.size() and puts the output into the appropriate column of means. this function outputs the matrix MEANS and the vector nsample - both as part of a list However, the vector nsample could be c(1,3,5) but I want the outputs to go into columns 1, 2 and 3 rather than 1,3,5 (which I'm not even sure would work anyway!) Any help would be great! If I leave the code as it is and use the vector data<-c(1,2,3) Then create.all.means(c(1,2),data,5) gives $MEANS [,1] [,2] [1,] 2.5 2.5 [2,] 1.0 1.0 [3,] 2.0 2.0 [4,] 2.0 2.0 [5,] 2.0 2.0 $nsample [1] 1 2 $std.dev1] 0.5477226 0.5477226[ which obviously isn't correct :( -- View this message in context: http://r.789695.n4.nabble.com/Matrix-manipulation-in-for-loop-tp3525849p3525849.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix evaluation using if function
Hi, thank you very much, both methods worked perfectly. Regards On Fri, Apr 29, 2011 at 4:17 PM, Berend Hasselman wrote: > > David Winsemius wrote: > > > > On Apr 29, 2011, at 4:27 AM, ivan wrote: > > > >> Hi All, > >> > >> I am trying to create a function which evaluates whether the values > >> (which > >> are equal to one) of a matrix are the same as their mirror values. > >> Consider > >> the following matrix: > >> > >>> n<-matrix(cbind(c(0,1,1),c(1,0,0),c(0,1,0)),3,3) > >>> colnames(n)<-cbind("A","B","C");rownames(n)<-cbind("A","B","C") > >>> n > >> A B C > >> A 0 1 0 > >> B 1 0 1 > >> C 1 0 0 > >> > >> Hence, since n[2,1] and n[1,2] are 1 and the same, the function should > >> return the name of the row of n[2,1]. I used the following function: > >> > >> for (i in length(rownames(n))) { > >> > >> for (j in length(colnames(n))){ > >> > >> if(n[i,j]==n[j,i]){ > >> > >> rownames(n)[[i]]->output} else {} > >> > >> } > >> > >> } > >> > >>> output > >> NULL > >> > >> The right answer would have been "B", though. > > > > Can you explain why "A" would not be an equally good answer to satisfy > > your problem set up? > > > > > which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) > >row col > > B 2 1 > > A 1 2 > > > rownames(which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) ) > > [1] "B" "A" > > > > # Which would seem to be the correct answer, but > > # This adds an additional constraint and also insures no diagonal > > elements > > > > > rownames(which(n == t(n) & col(n) != row(n) & lower.tri(n), > > arr.ind=TRUE) ) > > [1] "B" > > > > Wouldn't this do it too (dsince the diagonal is set to false by > lower.tri)?: > > rownames(which(n == t(n) & lower.tri(n), arr.ind=TRUE)) > > Berend > > > > -- > View this message in context: > http://r.789695.n4.nabble.com/matrix-evaluation-using-if-function-tp3483188p3483785.html > Sent from the R help mailing list archive at Nabble.com. > > __ > R-help@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. > [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix evaluation using if function
David Winsemius wrote: > > On Apr 29, 2011, at 4:27 AM, ivan wrote: > >> Hi All, >> >> I am trying to create a function which evaluates whether the values >> (which >> are equal to one) of a matrix are the same as their mirror values. >> Consider >> the following matrix: >> >>> n<-matrix(cbind(c(0,1,1),c(1,0,0),c(0,1,0)),3,3) >>> colnames(n)<-cbind("A","B","C");rownames(n)<-cbind("A","B","C") >>> n >> A B C >> A 0 1 0 >> B 1 0 1 >> C 1 0 0 >> >> Hence, since n[2,1] and n[1,2] are 1 and the same, the function should >> return the name of the row of n[2,1]. I used the following function: >> >> for (i in length(rownames(n))) { >> >> for (j in length(colnames(n))){ >> >> if(n[i,j]==n[j,i]){ >> >> rownames(n)[[i]]->output} else {} >> >> } >> >> } >> >>> output >> NULL >> >> The right answer would have been "B", though. > > Can you explain why "A" would not be an equally good answer to satisfy > your problem set up? > > > which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) >row col > B 2 1 > A 1 2 > > rownames(which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) ) > [1] "B" "A" > > # Which would seem to be the correct answer, but > # This adds an additional constraint and also insures no diagonal > elements > > > rownames(which(n == t(n) & col(n) != row(n) & lower.tri(n), > arr.ind=TRUE) ) > [1] "B" > Wouldn't this do it too (dsince the diagonal is set to false by lower.tri)?: rownames(which(n == t(n) & lower.tri(n), arr.ind=TRUE)) Berend -- View this message in context: http://r.789695.n4.nabble.com/matrix-evaluation-using-if-function-tp3483188p3483785.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix evaluation using if function
On Apr 29, 2011, at 4:27 AM, ivan wrote: Hi All, I am trying to create a function which evaluates whether the values (which are equal to one) of a matrix are the same as their mirror values. Consider the following matrix: n<-matrix(cbind(c(0,1,1),c(1,0,0),c(0,1,0)),3,3) colnames(n)<-cbind("A","B","C");rownames(n)<-cbind("A","B","C") n A B C A 0 1 0 B 1 0 1 C 1 0 0 Hence, since n[2,1] and n[1,2] are 1 and the same, the function should return the name of the row of n[2,1]. I used the following function: for (i in length(rownames(n))) { for (j in length(colnames(n))){ if(n[i,j]==n[j,i]){ rownames(n)[[i]]->output} else {} } } output NULL The right answer would have been "B", though. Can you explain why "A" would not be an equally good answer to satisfy your problem set up? > which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) row col B 2 1 A 1 2 > rownames(which(n == t(n) & col(n) != row(n) , arr.ind=TRUE) ) [1] "B" "A" # Which would seem to be the correct answer, but # This adds an additional constraint and also insures no diagonal elements > rownames(which(n == t(n) & col(n) != row(n) & lower.tri(n), arr.ind=TRUE) ) [1] "B" I simply do not see my mistake. I would rather program a problem correctly that hash through errors in loop logic. -- David Winsemius, MD West Hartford, CT __ R-help@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.
[R] matrix evaluation using if function
Hi All, I am trying to create a function which evaluates whether the values (which are equal to one) of a matrix are the same as their mirror values. Consider the following matrix: > n<-matrix(cbind(c(0,1,1),c(1,0,0),c(0,1,0)),3,3) > colnames(n)<-cbind("A","B","C");rownames(n)<-cbind("A","B","C") > n A B C A 0 1 0 B 1 0 1 C 1 0 0 Hence, since n[2,1] and n[1,2] are 1 and the same, the function should return the name of the row of n[2,1]. I used the following function: for (i in length(rownames(n))) { for (j in length(colnames(n))){ if(n[i,j]==n[j,i]){ rownames(n)[[i]]->output} else {} } } > output NULL The right answer would have been "B", though. I simply do not see my mistake. I am very greatful for suggestions. Thank you. [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix of higher order differences
Peter, I have indeed worked with Gregory-Newton and divided differences in my very first numerical analysis course a couple of decades ago! However, I am perplexed by the particular form of this matrix where the differences are stored along the diagonals. I know that this is not the *same* as the Wronskian, but was just wondering whether it is an established matrix that is some kind of an *ian* like Hermitian, Jacobian, Hessian, Wronskian, Laplacian, ... Best, Ravi. --- Ravi Varadhan, Ph.D. Assistant Professor, Division of Geriatric Medicine and Gerontology School of Medicine Johns Hopkins University Ph. (410) 502-2619 email: rvarad...@jhmi.edu -Original Message- From: peter dalgaard [mailto:pda...@gmail.com] Sent: Wednesday, April 27, 2011 4:59 PM To: Ravi Varadhan Cc: R Help Subject: Re: [R] matrix of higher order differences On Apr 27, 2011, at 21:34 , Ravi Varadhan wrote: > My apologies in advance for being a bit off-topic, but I could not quell my > curiosity. > > What might one do with a matrix of all order finite differences? It seems > that such a matrix might be related to the Wronskian (its discrete analogue, > perhaps). > > http://en.wikipedia.org/wiki/Wronskian Not quite, I think. This is one function at different values of x, the Wronskian is about n different functions. Tables of higher-order differences were used fundamentally for interpolation and error detection in tables of function values (remember those?), but rarely computed to the full extent - usually only until the effects of truncation set in and the differences start alternating in sign. > > Ravi. > --- > Ravi Varadhan, Ph.D. > Assistant Professor, > Division of Geriatric Medicine and Gerontology School of Medicine Johns > Hopkins University > > Ph. (410) 502-2619 > email: rvarad...@jhmi.edu > > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of Petr Savicky > Sent: Wednesday, April 27, 2011 11:01 AM > To: r-help@r-project.org > Subject: Re: [R] matrix of higher order differences > > On Wed, Apr 27, 2011 at 11:25:42AM +, Hans W Borchers wrote: >> Jeroen Ooms gmail.com> writes: >> >>> >>> Is there an easy way to turn a vector of length n into an n by n matrix, in >>> which the diagonal equals the vector, the first off diagonal equals the >>> first order differences, the second... etc. I.e. to do this more >>> efficiently: >>> >>> diffmatrix <- function(x){ >>> n <- length(x); >>> M <- diag(x); >>> for(i in 1:(n-1)){ >>> differences <- diff(x, dif=i); >>> for(j in 1:length(differences)){ >>> M[j,i+j] <- differences[j] >>> } >>> } >>> M[lower.tri(M)] <- t(M)[lower.tri(M)]; >>> return(M); >>> } >>> >>> x <- c(1,2,3,5,7,11,13,17,19); >>> diffmatrix(x); >>> >> >> I do not know whether you will call the appended version more elegant, >> but at least it is much faster -- up to ten times for length(x) = 1000, >> i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. >> I also considered col(), row() indexing: >> >>M[col(M) == row(M) + k] <- x >> >> Surprisingly (for me), this makes it even slower than your version with >> a double 'for' loop. >> >> -- Hans Werner >> >> # >> diffmatrix <- function(x){ >> n <- length(x) >> if (n == 1) return(x) >> >> M <- diag(x) >> for(i in 1:(n-1)){ >> x <- diff(x) # use 'diff' in a loop >> for(j in 1:(n-i)){ # length is known >> M[j, i+j] <- x[j] # and reuse x >> } >> } >> M[lower.tri(M)] <- t(M)[lower.tri(M)] >> return(M) >> } >> # > > Hi. > > The following avoids the inner loop and it was faster > for x of length 100 and 1000. > > diffmatrix2 <- function(x){ > n <- length(x) > if (n == 1) return(x) > A <- matrix(nrow=n+1, ncol=n) > for(i in 1:n){ > A[i, seq.int(along=x)] <- x > x <- diff(x) > } > M <- matrix(A, nrow=n, ncol=n) > M[upper.tri(M)] <- t(M)[upper.tri(M)] > return(M) > } > > Reorganizing an (n+1) x n matrix into an n x n matrix >
Re: [R] matrix of higher order differences
On Apr 27, 2011, at 21:34 , Ravi Varadhan wrote: > My apologies in advance for being a bit off-topic, but I could not quell my > curiosity. > > What might one do with a matrix of all order finite differences? It seems > that such a matrix might be related to the Wronskian (its discrete analogue, > perhaps). > > http://en.wikipedia.org/wiki/Wronskian Not quite, I think. This is one function at different values of x, the Wronskian is about n different functions. Tables of higher-order differences were used fundamentally for interpolation and error detection in tables of function values (remember those?), but rarely computed to the full extent - usually only until the effects of truncation set in and the differences start alternating in sign. > > Ravi. > --- > Ravi Varadhan, Ph.D. > Assistant Professor, > Division of Geriatric Medicine and Gerontology School of Medicine Johns > Hopkins University > > Ph. (410) 502-2619 > email: rvarad...@jhmi.edu > > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of Petr Savicky > Sent: Wednesday, April 27, 2011 11:01 AM > To: r-help@r-project.org > Subject: Re: [R] matrix of higher order differences > > On Wed, Apr 27, 2011 at 11:25:42AM +, Hans W Borchers wrote: >> Jeroen Ooms gmail.com> writes: >> >>> >>> Is there an easy way to turn a vector of length n into an n by n matrix, in >>> which the diagonal equals the vector, the first off diagonal equals the >>> first order differences, the second... etc. I.e. to do this more >>> efficiently: >>> >>> diffmatrix <- function(x){ >>> n <- length(x); >>> M <- diag(x); >>> for(i in 1:(n-1)){ >>> differences <- diff(x, dif=i); >>> for(j in 1:length(differences)){ >>> M[j,i+j] <- differences[j] >>> } >>> } >>> M[lower.tri(M)] <- t(M)[lower.tri(M)]; >>> return(M); >>> } >>> >>> x <- c(1,2,3,5,7,11,13,17,19); >>> diffmatrix(x); >>> >> >> I do not know whether you will call the appended version more elegant, >> but at least it is much faster -- up to ten times for length(x) = 1000, >> i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. >> I also considered col(), row() indexing: >> >>M[col(M) == row(M) + k] <- x >> >> Surprisingly (for me), this makes it even slower than your version with >> a double 'for' loop. >> >> -- Hans Werner >> >> # >> diffmatrix <- function(x){ >> n <- length(x) >> if (n == 1) return(x) >> >> M <- diag(x) >> for(i in 1:(n-1)){ >> x <- diff(x) # use 'diff' in a loop >> for(j in 1:(n-i)){ # length is known >> M[j, i+j] <- x[j] # and reuse x >> } >> } >> M[lower.tri(M)] <- t(M)[lower.tri(M)] >> return(M) >> } >> # > > Hi. > > The following avoids the inner loop and it was faster > for x of length 100 and 1000. > > diffmatrix2 <- function(x){ > n <- length(x) > if (n == 1) return(x) > A <- matrix(nrow=n+1, ncol=n) > for(i in 1:n){ > A[i, seq.int(along=x)] <- x > x <- diff(x) > } > M <- matrix(A, nrow=n, ncol=n) > M[upper.tri(M)] <- t(M)[upper.tri(M)] > return(M) > } > > Reorganizing an (n+1) x n matrix into an n x n matrix > shifts i-th column by (i-1) downwards. In particular, > the first row becomes the main diagonal. The initial > part of each of the remaining rows becomes a diagonal > starting at the first component of the original row. > > Petr Savicky. > > __ > R-help@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. > > __ > R-help@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. -- Peter Dalgaard Center for Statistics, Copenhagen Business School Solbjerg Plads 3, 2000 Frederiksberg, Denmark Phone: (+45)38153501 Email: pd@cbs.dk Priv: pda...@gmail.com __ R-help@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.
Re: [R] matrix of higher order differences
My apologies in advance for being a bit off-topic, but I could not quell my curiosity. What might one do with a matrix of all order finite differences? It seems that such a matrix might be related to the Wronskian (its discrete analogue, perhaps). http://en.wikipedia.org/wiki/Wronskian Ravi. --- Ravi Varadhan, Ph.D. Assistant Professor, Division of Geriatric Medicine and Gerontology School of Medicine Johns Hopkins University Ph. (410) 502-2619 email: rvarad...@jhmi.edu -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Petr Savicky Sent: Wednesday, April 27, 2011 11:01 AM To: r-help@r-project.org Subject: Re: [R] matrix of higher order differences On Wed, Apr 27, 2011 at 11:25:42AM +, Hans W Borchers wrote: > Jeroen Ooms gmail.com> writes: > > > > > Is there an easy way to turn a vector of length n into an n by n matrix, in > > which the diagonal equals the vector, the first off diagonal equals the > > first order differences, the second... etc. I.e. to do this more > > efficiently: > > > > diffmatrix <- function(x){ > > n <- length(x); > > M <- diag(x); > > for(i in 1:(n-1)){ > > differences <- diff(x, dif=i); > > for(j in 1:length(differences)){ > > M[j,i+j] <- differences[j] > > } > > } > > M[lower.tri(M)] <- t(M)[lower.tri(M)]; > > return(M); > > } > > > > x <- c(1,2,3,5,7,11,13,17,19); > > diffmatrix(x); > > > > I do not know whether you will call the appended version more elegant, > but at least it is much faster -- up to ten times for length(x) = 1000, > i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. > I also considered col(), row() indexing: > > M[col(M) == row(M) + k] <- x > > Surprisingly (for me), this makes it even slower than your version with > a double 'for' loop. > > -- Hans Werner > > # > diffmatrix <- function(x){ > n <- length(x) > if (n == 1) return(x) > > M <- diag(x) > for(i in 1:(n-1)){ > x <- diff(x) # use 'diff' in a loop > for(j in 1:(n-i)){ # length is known > M[j, i+j] <- x[j] # and reuse x > } > } > M[lower.tri(M)] <- t(M)[lower.tri(M)] > return(M) > } > # Hi. The following avoids the inner loop and it was faster for x of length 100 and 1000. diffmatrix2 <- function(x){ n <- length(x) if (n == 1) return(x) A <- matrix(nrow=n+1, ncol=n) for(i in 1:n){ A[i, seq.int(along=x)] <- x x <- diff(x) } M <- matrix(A, nrow=n, ncol=n) M[upper.tri(M)] <- t(M)[upper.tri(M)] return(M) } Reorganizing an (n+1) x n matrix into an n x n matrix shifts i-th column by (i-1) downwards. In particular, the first row becomes the main diagonal. The initial part of each of the remaining rows becomes a diagonal starting at the first component of the original row. Petr Savicky. __ R-help@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. __ R-help@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.
Re: [R] matrix of higher order differences
On Wed, Apr 27, 2011 at 11:25:42AM +, Hans W Borchers wrote: > Jeroen Ooms gmail.com> writes: > > > > > Is there an easy way to turn a vector of length n into an n by n matrix, in > > which the diagonal equals the vector, the first off diagonal equals the > > first order differences, the second... etc. I.e. to do this more > > efficiently: > > > > diffmatrix <- function(x){ > > n <- length(x); > > M <- diag(x); > > for(i in 1:(n-1)){ > > differences <- diff(x, dif=i); > > for(j in 1:length(differences)){ > > M[j,i+j] <- differences[j] > > } > > } > > M[lower.tri(M)] <- t(M)[lower.tri(M)]; > > return(M); > > } > > > > x <- c(1,2,3,5,7,11,13,17,19); > > diffmatrix(x); > > > > I do not know whether you will call the appended version more elegant, > but at least it is much faster -- up to ten times for length(x) = 1000, > i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. > I also considered col(), row() indexing: > > M[col(M) == row(M) + k] <- x > > Surprisingly (for me), this makes it even slower than your version with > a double 'for' loop. > > -- Hans Werner > > # > diffmatrix <- function(x){ > n <- length(x) > if (n == 1) return(x) > > M <- diag(x) > for(i in 1:(n-1)){ > x <- diff(x) # use 'diff' in a loop > for(j in 1:(n-i)){ # length is known > M[j, i+j] <- x[j] # and reuse x > } > } > M[lower.tri(M)] <- t(M)[lower.tri(M)] > return(M) > } > # Hi. The following avoids the inner loop and it was faster for x of length 100 and 1000. diffmatrix2 <- function(x){ n <- length(x) if (n == 1) return(x) A <- matrix(nrow=n+1, ncol=n) for(i in 1:n){ A[i, seq.int(along=x)] <- x x <- diff(x) } M <- matrix(A, nrow=n, ncol=n) M[upper.tri(M)] <- t(M)[upper.tri(M)] return(M) } Reorganizing an (n+1) x n matrix into an n x n matrix shifts i-th column by (i-1) downwards. In particular, the first row becomes the main diagonal. The initial part of each of the remaining rows becomes a diagonal starting at the first component of the original row. Petr Savicky. __ R-help@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.
Re: [R] matrix of higher order differences
On Apr 27, 2011, at 7:25 AM, Hans W Borchers wrote: Jeroen Ooms gmail.com> writes: Is there an easy way to turn a vector of length n into an n by n matrix, in which the diagonal equals the vector, the first off diagonal equals the first order differences, the second... etc. I.e. to do this more efficiently: diffmatrix <- function(x){ n <- length(x); M <- diag(x); for(i in 1:(n-1)){ differences <- diff(x, dif=i); for(j in 1:length(differences)){ M[j,i+j] <- differences[j] } } M[lower.tri(M)] <- t(M)[lower.tri(M)]; return(M); } x <- c(1,2,3,5,7,11,13,17,19); diffmatrix(x); I do not know whether you will call the appended version more elegant, but at least it is much faster -- up to ten times for length(x) = 1000, i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. I also considered col(), row() indexing: M[col(M) == row(M) + k] <- x Surprisingly (for me), this makes it even slower than your version with a double 'for' loop. Every call to row() or col() creates a matrix of the same size as M. It might speed up if you created them outside the loop. -- Hans Werner # diffmatrix <- function(x){ n <- length(x) if (n == 1) return(x) M <- diag(x) for(i in 1:(n-1)){ x <- diff(x) # use 'diff' in a loop for(j in 1:(n-i)){ # length is known M[j, i+j] <- x[j] # and reuse x } } M[lower.tri(M)] <- t(M)[lower.tri(M)] return(M) } # David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] matrix of higher order differences
Jeroen Ooms gmail.com> writes: > > Is there an easy way to turn a vector of length n into an n by n matrix, in > which the diagonal equals the vector, the first off diagonal equals the > first order differences, the second... etc. I.e. to do this more > efficiently: > > diffmatrix <- function(x){ > n <- length(x); > M <- diag(x); > for(i in 1:(n-1)){ > differences <- diff(x, dif=i); > for(j in 1:length(differences)){ > M[j,i+j] <- differences[j] > } > } > M[lower.tri(M)] <- t(M)[lower.tri(M)]; > return(M); > } > > x <- c(1,2,3,5,7,11,13,17,19); > diffmatrix(x); > I do not know whether you will call the appended version more elegant, but at least it is much faster -- up to ten times for length(x) = 1000, i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix. I also considered col(), row() indexing: M[col(M) == row(M) + k] <- x Surprisingly (for me), this makes it even slower than your version with a double 'for' loop. -- Hans Werner # diffmatrix <- function(x){ n <- length(x) if (n == 1) return(x) M <- diag(x) for(i in 1:(n-1)){ x <- diff(x) # use 'diff' in a loop for(j in 1:(n-i)){ # length is known M[j, i+j] <- x[j] # and reuse x } } M[lower.tri(M)] <- t(M)[lower.tri(M)] return(M) } # __ R-help@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.
[R] matrix of higher order differences
Is there an easy way to turn a vector of length n into an n by n matrix, in which the diagonal equals the vector, the first off diagonal equals the first order differences, the second... etc. I.e. to do this more efficiently: diffmatrix <- function(x){ n <- length(x); M <- diag(x); for(i in 1:(n-1)){ differences <- diff(x, dif=i); for(j in 1:length(differences)){ M[j,i+j] <- differences[j] } } M[lower.tri(M)] <- t(M)[lower.tri(M)]; return(M); } x <- c(1,2,3,5,7,11,13,17,19); diffmatrix(x); -- View this message in context: http://r.789695.n4.nabble.com/matrix-of-higher-order-differences-tp3477339p3477339.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix
On Tue, Apr 26, 2011 at 2:28 PM, Val wrote: > Hi all, > > Assume I have a matrix > xv= [1 0 0 0 0 12, > 0 1 0 0 0 10, > * 0 0 1 0 0 -9,* > 0 0 0 1 0 20, > * 0 0 0 0 1 -5]* > > if the last column of "xv" less than 0 then I want to set zero the entire > row. > The desired output looks like the following. In this case row 3 and row 5 > are set zero. > > [ 1 0 0 0 0 12, > 0 1 0 0 0 10, > * 0 0 0 0 0 0,* > 0 0 0 1 0 20, > * 0 0 0 0 0 0*] > > I used ifelse command but did not work > > Is there another command to do that? Yes. nc = ncol(xv) result = xv; result[ xv[, nc] <0, ] = 0 HTH, Peter __ R-help@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.
Re: [R] matrix
Try this: replace(m, m[,ncol(m)] < 0, 0) On Tue, Apr 26, 2011 at 6:28 PM, Val wrote: > Hi all, > > Assume I have a matrix > xv= [1 0 0 0 0 12, > 0 1 0 0 0 10, > * 0 0 1 0 0 -9,* > 0 0 0 1 0 20, > * 0 0 0 0 1 -5]* > > if the last column of "xv" less than 0 then I want to set zero the entire > row. > The desired output looks like the following. In this case row 3 and row 5 > are set zero. > > [ 1 0 0 0 0 12, > 0 1 0 0 0 10, > * 0 0 0 0 0 0,* > 0 0 0 1 0 20, > * 0 0 0 0 0 0*] > > I used ifelse command but did not work > > Is there another command to do that? > > Thanks in advance > \ > > [[alternative HTML version deleted]] > > __ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O __ R-help@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.
[R] matrix
Hi all, Assume I have a matrix xv= [1 0 0 0 0 12, 0 1 0 0 0 10, *0 0 1 0 0 -9,* 0 0 0 1 0 20, * 0 0 0 0 1 -5]* if the last column of "xv" less than 0 then I want to set zero the entire row. The desired output looks like the following. In this case row 3 and row 5 are set zero. [ 1 0 0 0 0 12, 0 1 0 0 0 10, * 0 0 0 0 0 0,* 0 0 0 1 0 20, * 0 0 0 0 0 0*] I used ifelse command but did not work Is there another command to do that? Thanks in advance \ [[alternative HTML version deleted]] __ R-help@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.
Re: [R] Matrix package transpose
On Wed, Apr 20, 2011 at 8:37 AM, Tobias Abenius wrote: > Since I installed R 2.13 I cannot use the transpose method "t" on sparse > matrices inside my package. Outside the package works. Is there something > new that I have to import methods? Can I then import everything from the > Matrix package? The problem is that R tries to use t.default which of course > doesn't work. As the tag line on each message says: > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. Please provide an example. It will also help to include the output of sessionInfo() so we can determine exactly which version of R and the Matrix package you are using on what platform. Also try > find("t") [1] "package:Matrix" "package:base" to see which version of "t" is the first on the search path. It seems to still be working for me, but "outside the package". > library(Matrix) Loading required package: lattice Attaching package: 'Matrix' The following object(s) are masked from 'package:base': det > sessionInfo() R version 2.13.0 (2011-04-13) Platform: x86_64-pc-linux-gnu (64-bit) locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=C LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=en_US.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] Matrix_0.9996875-0 lattice_0.19-17 loaded via a namespace (and not attached): [1] grid_2.13.0 > example(spMatrix) ... output omitted > A 10 x 20 sparse Matrix of class "dgTMatrix" [1,] . 7 . . . . . . . . . . . . . . . . . . [2,] . . . . . . . . . . . . . . . . . . . . [3,] . . . . . . . . 14 . . . . . . . . . . . [4,] . . . . . 21 . . . . . . . . . . . . . . [5,] . . . . . . 28 . . . . . . . . . . . . . [6,] . . . . . . . 35 . . . . . . . . . . . . [7,] . . . . . . . . 42 . . . . . . . . . . . [8,] . . . . . . . . . 49 . . . . . . . . . . [9,] . . . . . . . . . . . . . . . . . . . . [10,] . . . . . . . . . . . . . . . . . . . . > t(A) 20 x 10 sparse Matrix of class "dgTMatrix" [1,] . . . . . . . . . . [2,] 7 . . . . . . . . . [3,] . . . . . . . . . . [4,] . . . . . . . . . . [5,] . . . . . . . . . . [6,] . . . 21 . . . . . . [7,] . . . . 28 . . . . . [8,] . . . . . 35 . . . . [9,] . . 14 . . . 42 . . . [10,] . . . . . . . 49 . . [11,] . . . . . . . . . . [12,] . . . . . . . . . . [13,] . . . . . . . . . . [14,] . . . . . . . . . . [15,] . . . . . . . . . . [16,] . . . . . . . . . . [17,] . . . . . . . . . . [18,] . . . . . . . . . . [19,] . . . . . . . . . . [20,] . . . . . . . . . . __ R-help@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.
[R] Matrix package transpose
Hi, Since I installed R 2.13 I cannot use the transpose method "t" on sparse matrices inside my package. Outside the package works. Is there something new that I have to import methods? Can I then import everything from the Matrix package? The problem is that R tries to use t.default which of course doesn't work. Happy easter, Tobias -- Tobias Abenius Ph.D. Student, M.Sc. in Computer Science Mathematical Statistics Mathematical Sciences University of Gothenburg __ R-help@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.
Re: [R] Matrix manipulation
HI, here is another solution: int <- sample(1:20,10) int [1] 10 4 5 2 14 17 9 11 16 13 mat<-matrix(11:30,ncol=4) mat [,1] [,2] [,3] [,4] [1,] 11 16 21 26 [2,] 12 17 22 27 [3,] 13 18 23 28 [4,] 14 19 24 29 [5,] 15 20 25 30 mat[apply(mat,1, function(x) any(int==x[1])),] [,1] [,2] [,3] [,4] [1,] 11 16 21 26 [2,] 13 18 23 28 [3,] 14 19 24 29 Andrija On Sat, Apr 2, 2011 at 7:08 AM, Joseph N. Paulson wrote: > Hi all! > > I have a vector, let's say for example int <- sample(1:20,10); > for now: > > now I have a matrix... > M = m x n > where the first column is a "feature" column and most likely shares at > least > one of the int (interesting) numbers. > > I want to extract the rows where int[] = M[,1] > > I thought: > rownames(int)<-int; > rownames(M)<-M[,1]; > > M[rownames(int),] would work, but it doesn't... (I assume because I have > rownames(int) that are not found in M[,1]. Neither does, > rownames(M)==rownames(int)... > > Any help would be greatly appreciated! > > Thank you! > >[[alternative HTML version deleted]] > > __ > R-help@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. > [[alternative HTML version deleted]] __ R-help@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.
Re: [R] Matrix manipulation
Hi: Here' s one approach: > int <- sample(1:20,10) > m <- matrix(sample(1:40, 20), nrow = 10) > int [1] 7 12 4 6 1 19 17 20 15 5 > m [,1] [,2] [1,]9 15 [2,] 23 32 [3,] 40 14 [4,] 19 38 [5,] 286 [6,] 26 18 [7,] 34 22 [8,]7 35 [9,] 213 [10,] 39 12 > m[m[, 1] %in% int, ] [,1] [,2] [1,] 19 38 [2,]7 35 HTH, Dennis On Fri, Apr 1, 2011 at 10:08 PM, Joseph N. Paulson wrote: > Hi all! > > I have a vector, let's say for example int <- sample(1:20,10); > for now: > > now I have a matrix... > M = m x n > where the first column is a "feature" column and most likely shares at > least > one of the int (interesting) numbers. > > I want to extract the rows where int[] = M[,1] > > I thought: > rownames(int)<-int; > rownames(M)<-M[,1]; > > M[rownames(int),] would work, but it doesn't... (I assume because I have > rownames(int) that are not found in M[,1]. Neither does, > rownames(M)==rownames(int)... > > Any help would be greatly appreciated! > > Thank you! > >[[alternative HTML version deleted]] > > __ > R-help@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. > [[alternative HTML version deleted]] __ R-help@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.
[R] Matrix manipulation
Hi all! I have a vector, let's say for example int <- sample(1:20,10); for now: now I have a matrix... M = m x n where the first column is a "feature" column and most likely shares at least one of the int (interesting) numbers. I want to extract the rows where int[] = M[,1] I thought: rownames(int)<-int; rownames(M)<-M[,1]; M[rownames(int),] would work, but it doesn't... (I assume because I have rownames(int) that are not found in M[,1]. Neither does, rownames(M)==rownames(int)... Any help would be greatly appreciated! Thank you! [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix inverstion
On Mon, Mar 28, 2011 at 04:51:00PM +0200, Rosario Garcia Gil wrote: > Hello > > I have this matrix which I am trying to invert. I get a message about > reciprocal condition number, what that does mean? > > > XT_X > [,1] [,2] [,3] [,4] [,5] > [1,]30021 > [2,]02011 > [3,]00211 > [4,]21140 > [5,]11103 > > iXT_X <- solve(XT_X) > Error in solve.default(XT_X) : > system is computationally singular: reciprocal condition number = > 1.11022e-17 This matrix is exactly singular. For example, the sum of the first three rows is equal to the sum of the last two. cbind(1, 1, 1, -1, -1) %*% XT_X [,1] [,2] [,3] [,4] [,5] [1,]00000 For matrices with small integer entries, a test for singularity may be done using det(). det(XT_X) [1] 8.881784e-15 Since the exact determinant is an integer, it has to be zero and the difference from zero is due to rounding error. Hope this helps. Petr Savicky. __ R-help@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.
Re: [R] matrix inverstion
Daniel Nordlund frontier.com> writes: > > On Behalf Of Rosario Garcia Gil > > I have this matrix which I am trying to invert. I get a message about > > reciprocal condition number, what that does mean? [snip] > > Well, it means exactly what the message says. Within the precision of your computer, the matrix is singular > and has no inverse. If you try the following code you will see that column 1 is perfectly correlated with the > remaining columns. > > summary(lm(XT_X [,1] ~ XT_X[,-1])) > Depending on what you're trying to do, you might try the generalized inverse in the MASS package (MASS::ginv). __ R-help@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.
Re: [R] matrix inverstion
> -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of Rosario Garcia Gil > Sent: Monday, March 28, 2011 7:51 AM > To: r-help@r-project.org > Subject: [R] matrix inverstion > > Hello > > I have this matrix which I am trying to invert. I get a message about > reciprocal condition number, what that does mean? > > > XT_X > [,1] [,2] [,3] [,4] [,5] > [1,]30021 > [2,]02011 > [3,]00211 > [4,]21140 > [5,]11103 > > iXT_X <- solve(XT_X) > Error in solve.default(XT_X) : > system is computationally singular: reciprocal condition number = > 1.11022e-17 > > Well, it means exactly what the message says. Within the precision of your computer, the matrix is singular and has no inverse. If you try the following code you will see that column 1 is perfectly correlated with the remaining columns. summary(lm(XT_X [,1] ~ XT_X[,-1])) Hope this is helpful, Dan Daniel Nordlund Bothell, WA USA __ R-help@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.
[R] matrix inverstion
Hello I have this matrix which I am trying to invert. I get a message about reciprocal condition number, what that does mean? > XT_X [,1] [,2] [,3] [,4] [,5] [1,]30021 [2,]02011 [3,]00211 [4,]21140 [5,]11103 > iXT_X <- solve(XT_X) Error in solve.default(XT_X) : system is computationally singular: reciprocal condition number = 1.11022e-17 Thanks Rosario __ R-help@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.
Re: [R] Matrix building to remove for loops
Thanks, we're almost there. The 3rd statement needs to satisfy fi_2[r,c]<-fi_2[c,r] where rwrote: > Try this: > > fi_2 <- diag(1, i) > fi_2[lower.tri(fi_2)] <- 1 - runif(sum(lower.tri(fi_2))) ^ .5 > fi_2[upper.tri(fi_2)] <- fi_2[lower.tri(fi_2)] > > On Tue, Mar 15, 2011 at 7:51 PM, Brian Pellerin < > brianpatrickpelle...@gmail.com> wrote: > >> Hello R users, >> >> I would like to reduce the number of for loops in my code. I build these >> matrices (5 times). The main diagonal are 1s and the two sides along >> the >> main diagonal mirror each other as follows: >> >> >> i<-5 >> fi<-matrix(0,nrow=i,ncol=i)#floral inhibition matrix for(r in 1:i){ for(c >> in >> 1:i){ if(r==c){ fi[r,c]<-1 }else if(r> fi[r,c]<-fi[c,r] } } } >> fi >> >> Any thoughts? >> >> Sincerely, >> Brian >> >>[[alternative HTML version deleted]] >> >> __ >> R-help@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. >> > > > > -- > Henrique Dallazuanna > Curitiba-Paraná-Brasil > 25° 25' 40" S 49° 16' 22" O > [[alternative HTML version deleted]] __ R-help@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.
Re: [R] Matrix building to remove for loops
Try this: fi_2 <- diag(1, i) fi_2[lower.tri(fi_2)] <- 1 - runif(sum(lower.tri(fi_2))) ^ .5 fi_2[upper.tri(fi_2)] <- fi_2[lower.tri(fi_2)] On Tue, Mar 15, 2011 at 7:51 PM, Brian Pellerin < brianpatrickpelle...@gmail.com> wrote: > Hello R users, > > I would like to reduce the number of for loops in my code. I build these > matrices (5 times). The main diagonal are 1s and the two sides along > the > main diagonal mirror each other as follows: > > > i<-5 > fi<-matrix(0,nrow=i,ncol=i)#floral inhibition matrix for(r in 1:i){ for(c > in > 1:i){ if(r==c){ fi[r,c]<-1 }else if(r fi[r,c]<-fi[c,r] } } } > fi > > Any thoughts? > > Sincerely, > Brian > >[[alternative HTML version deleted]] > > __ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]] __ R-help@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.
[R] Matrix building to remove for loops
Hello R users, I would like to reduce the number of for loops in my code. I build these matrices (5 times). The main diagonal are 1s and the two sides along the main diagonal mirror each other as follows: i<-5 fi<-matrix(0,nrow=i,ncol=i)#floral inhibition matrix for(r in 1:i){ for(c in 1:i){ if(r==c){ fi[r,c]<-1 }else if(rhttps://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.
Re: [R] Matrix Help
On Sun, Feb 20, 2011 at 2:56 PM, Dmitry Berman wrote: > On Sun, Feb 20, 2011 at 5:55 PM, Dmitry Berman wrote: > >> Listers, >> >> I have a simple matrix: >> >> -- >> m <-c(1:7) >> m <- cbind(m) >> >> m >> [1,] 1 >> [2,] 2 >> [3,] 3 >> [4,] 4 >> [5,] 5 >> [6,] 6 >> [7,] 7 >> --- >> >> I want to add a second column using: >> >> >> > m[,2] <- cbind(m,8:14) > But I get the error: > Error in m[, 2] <- cbind(m, 8:14) : subscript out of bounds > > What am I doing wrong? > > Thanks > > [[alternative HTML version deleted]] > > __ > R-help@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. > How about: m1 <-c(1:7) M1<-cbind(m1) M1 m2 <-c(2:8) M2<-cbind(m2) M2 cbind(M1,M2) __ R-help@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.
Re: [R] Matrix Help
On Feb 20, 2011, at 5:56 PM, Dmitry Berman wrote: On Sun, Feb 20, 2011 at 5:55 PM, Dmitry Berman wrote: Listers, I have a simple matrix: -- m <-c(1:7) m <- cbind(m) m [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 [6,] 6 [7,] 7 --- I want to add a second column using: m[,2] <- cbind(m,8:14) Don't reference the column number on the LHS: m <- 1:7 m <- cbind(m, 8:14) > m m [1,] 1 8 [2,] 2 9 [3,] 3 10 [4,] 4 11 [5,] 5 12 [6,] 6 13 [7,] 7 14 But I get the error: Error in m[, 2] <- cbind(m, 8:14) : subscript out of bounds What am I doing wrong? Thanks [[alternative HTML version deleted]] __ R-help@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. David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] Matrix Help
On Sun, Feb 20, 2011 at 5:55 PM, Dmitry Berman wrote: > Listers, > > I have a simple matrix: > > -- > m <-c(1:7) > m <- cbind(m) > > m > [1,] 1 > [2,] 2 > [3,] 3 > [4,] 4 > [5,] 5 > [6,] 6 > [7,] 7 > --- > > I want to add a second column using: > > > m[,2] <- cbind(m,8:14) But I get the error: Error in m[, 2] <- cbind(m, 8:14) : subscript out of bounds What am I doing wrong? Thanks [[alternative HTML version deleted]] __ R-help@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.
[R] Matrix Help
Listers, I have a simple matrix: -- m <-c(1:7) m <- cbind(m) m [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 [6,] 6 [7,] 7 --- I want to add a second column using: [[alternative HTML version deleted]] __ R-help@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.
Re: [R] Matrix in R
On Feb 18, 2011, at 9:32 AM, danielepippo wrote: but if in my function pp_ris2[i,j]=myfunction} must be the indexes 0-0,0-1,0-2,0-3, ? I came across a posting in r-help that called this package "blasphemy": http://cran.r-project.org/web/packages/Oarray/index.html -- David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] Matrix in R
On Feb 18, 2011, at 9:32 AM, danielepippo wrote: but if in my function pp_ris2[i,j]=myfunction} must be the indexes 0-0,0-1,0-2,0-3, ? From a search of RSiteSearch() that started with with terms: zero matrix indexing http://finzi.psych.upenn.edu/R/Rhelp02/archive/39031.html http://finzi.psych.upenn.edu/R/Rhelp02/archive/26476.html http://finzi.psych.upenn.edu/R/Rhelp02/archive/32960.html -- View this message in context: http://r.789695.n4.nabble.com/Matrix-in-R-tp3312748p3312780.html Sent from the R help mailing list archive at Nabble.com. -- David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] Matrix in R
On Fri, Feb 18, 2011 at 06:32:01AM -0800, danielepippo wrote: > > but if in my function > pp_ris2[i,j]=myfunction} > must be the indexes 0-0,0-1,0-2,0-3, ? You'll have to take care of that yourself with a bit of index arithmetics. It's the same you encounter in C, if you are modelling something that would like to be indexed starting with 1 - just the other way round. cu Philipp -- Dr. Philipp Pagel Lehrstuhl für Genomorientierte Bioinformatik Technische Universität München Wissenschaftszentrum Weihenstephan Maximus-von-Imhof-Forum 3 85354 Freising, Germany http://webclu.bio.wzw.tum.de/~pagel/ __ R-help@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.
[R] Matrix in R
Hi everyone, I'm building a matrix in R with a cycle for like this: pp_ris2=matrix(NA,6,6) for(i in 0:6){ for(j in 0:6){ if(i>j){ pp_ris2[i,j]=myfunction} else if(i==j){ print(c(i,j)) pp_ris2[i,j]=myfunction} }} but the result is: [,1] [,2] [,3][,4] [,5][,6] [1,] 0.062 NaNNaNNaN NaN NaN [2,] 0.083 0.022 NaNNaN NaN NaN [3,] 0.072 0.022 0.004 NaN NaN NaN [4,] 0.046 0.016 0.003 0.001 NaN NaN [5,] 0.023 0.009 0.002 0.000 0 NaN [6,] 0.010 0.004 0.001 0.000 00 my problem is in the first column and row because in this matrix there are not the column and the row with i=0 and j=0. Can anyone help me please? thanks a lot -- View this message in context: http://r.789695.n4.nabble.com/Matrix-in-R-tp3312748p3312748.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] Matrix in R
but if in my function pp_ris2[i,j]=myfunction} must be the indexes 0-0,0-1,0-2,0-3, ? -- View this message in context: http://r.789695.n4.nabble.com/Matrix-in-R-tp3312748p3312780.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] Matrix in R
danielepippo wrote: > >I'm building a matrix in R with a cycle for like this: > pp_ris2=matrix(NA,6,6) > for(i in 0:6){ > . > R is not like c, indexing starts with 1. Dieter -- View this message in context: http://r.789695.n4.nabble.com/Matrix-in-R-tp3312748p3312764.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] Matrix of Matrices?
On Tue, Feb 15, 2011 at 09:40:54AM -0800, Alaios wrote: > Thank you very much for your help again. > One more question is that after I have that list of matrices what is the > easiest way to find the minimun and maximum values of ALL the matrices in > that list? Try the following. # get a list of random matrices rndmat <- function() matrix(runif(4), 2, 2) lst <- replicate(4, rndmat(), simplify=FALSE) # maximum of all components max(unlist(lst)) # vector of the maxima sapply(lst, max) Hope this helps. Petr Savicky. __ R-help@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.
Re: [R] Matrix of Matrices?
On Fri, Feb 11, 2011 at 06:17:16AM -0800, Alaios wrote: > Thanks that did the work. Once I have that list what is the easiest way to > export the structure as well as the contents (numbers) into a file. > > The purpose is to share that file with a colleague and ask him to load that > variable with its contents and structure. Any R object can be stored to a file using save() and read back using load(). Petr Savicky. __ R-help@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.
Re: [R] Matrix of Matrices?
Thanks that did the work. Once I have that list what is the easiest way to export the structure as well as the contents (numbers) into a file. The purpose is to share that file with a colleague and ask him to load that variable with its contents and structure. Best Regards Alex --- On Fri, 2/11/11, Petr Savicky wrote: > From: Petr Savicky > Subject: Re: [R] Matrix of Matrices? > To: r-help@r-project.org > Date: Friday, February 11, 2011, 12:22 PM > On Thu, Feb 10, 2011 at 11:54:50PM > -0800, Alaios wrote: > > Dear all I have a few matrices that I would like to > store alltogether under a bigger object. > > My matrixes with the same name were calculated inside > a loop like > > > > for (few times){ > > > > estimatedsr<- this is my matrix > > savematrixasimagefile(); > > > > > > } > > > > which means that I was losing all that instances. > > What can I do to keep all these matrices? ( I do not > know in advance their number, so I can not preallocate > space). > > How can I store them and adress them back again? > > > > I would like to thank you in advance in your help > > Hello. > > A possible approach is to use list (see ?list). > > lst <- list() > lst[[1]] <- rbind(c(1, 2), c(1, 2)) > lst[[2]] <- rbind(c(3, 3), c(4, 4)) > lst > > [[1]] > [,1] [,2] > [1,] 1 2 > [2,] 1 2 > > [[2]] > [,1] [,2] > [1,] 3 3 > [2,] 4 4 > > If you know in advance an upper bound on the number of > matrices, > then it is possible to use an array (see ?array). For > example > storing two matrices 2 x 2 may be done as follows > > a <- array(dim=c(2, 2, 2)) > a[,,1] <- rbind(c(1, 2), c(1, 2)) > a[,,2] <- rbind(c(3, 3), c(4, 4)) > a > > , , 1 > > [,1] [,2] > [1,] 1 2 > [2,] 1 2 > > , , 2 > > [,1] [,2] > [1,] 3 3 > [2,] 4 4 > > Hope this helps. > > Petr Savicky. > > __ > R-help@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. > Don't get soaked. Take a quick peek at the forecast with uts/#loc_weather __ R-help@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.
Re: [R] Matrix of Matrices?
On Thu, Feb 10, 2011 at 11:54:50PM -0800, Alaios wrote: > Dear all I have a few matrices that I would like to store alltogether under a > bigger object. > My matrixes with the same name were calculated inside a loop like > > for (few times){ > >estimatedsr<- this is my matrix >savematrixasimagefile(); > > > } > > which means that I was losing all that instances. > What can I do to keep all these matrices? ( I do not know in advance their > number, so I can not preallocate space). > How can I store them and adress them back again? > > I would like to thank you in advance in your help Hello. A possible approach is to use list (see ?list). lst <- list() lst[[1]] <- rbind(c(1, 2), c(1, 2)) lst[[2]] <- rbind(c(3, 3), c(4, 4)) lst [[1]] [,1] [,2] [1,]12 [2,]12 [[2]] [,1] [,2] [1,]33 [2,]44 If you know in advance an upper bound on the number of matrices, then it is possible to use an array (see ?array). For example storing two matrices 2 x 2 may be done as follows a <- array(dim=c(2, 2, 2)) a[,,1] <- rbind(c(1, 2), c(1, 2)) a[,,2] <- rbind(c(3, 3), c(4, 4)) a , , 1 [,1] [,2] [1,]12 [2,]12 , , 2 [,1] [,2] [1,]33 [2,]44 Hope this helps. Petr Savicky. __ R-help@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.
[R] Matrix of Matrices?
Dear all I have a few matrices that I would like to store alltogether under a bigger object. My matrixes with the same name were calculated inside a loop like for (few times){ estimatedsr<- this is my matrix savematrixasimagefile(); } which means that I was losing all that instances. What can I do to keep all these matrices? ( I do not know in advance their number, so I can not preallocate space). How can I store them and adress them back again? I would like to thank you in advance in your help Best Regards Alex __ R-help@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.
Re: [R] Unusual slowing of R matrix multiplication version 2.12.1 (2010-10-15) vs 2.12.0
You'll need to ask the person who built R (you haven't told us). If this was a binary CRAN build, you are asked to discuss that only on R-sig-mac, and you will find plenty of discussion on that list's archives. Note that - this is Mac-specific (not mentioned in your subject line) - it even depends on the chipset of the Macs in question. On Mon, 7 Feb 2011, Joseph Kunkel wrote: R Version 2.12.1 (2010-10-15) vs 2.12.0 has slowed down 8 fold for dual core and 17 fold for dual-core-dual-processor Macs. I have checked this result on 3 different macs using the following R-script: Using Version 2.12.0 on a dual core dual processor Mac: source("http://www.bio.umass.edu/biology/kunkel/pub/R/CuriousResult.R";) matrix multiplication 43.543 1.308 14.788 tcrossprod 41.147 1.286 11.9 transposition and reuse40.407 3.525 43.606 elementwise after reshape 21.474 1.828 23.124 columnwise sapply 34.695 32.35 66.592 for loop over columns 37.237 29.471 67.2 On the same day upgrading to 2.12.1 on the same dual core dual processor Mac: source("http://www.bio.umass.edu/biology/kunkel/pub/R/CuriousResult.R";) matrix multiplication 256.775 2.178 256.919 tcrossprod246.609 1.987 247.075 transposition and reuse39.622 4.602 43.883 elementwise after reshape 21.017 2.343 23.258 columnwise sapply39.393 37.069 75.834 for loop over columns 35.461 33.155 68.165 It seems clear that the upgrade to 2.12.1 has resulted in matrix multiplication using only one core. Notice that the other techniques that avoid matrix multiplication seem to stay the same but the two approaches that use matrix multiply have degraded worse than the expected loss of just 4 fold. Is it possible that a different matrix multiply library was used in changing from version 2.12.0 to 2.12.1? Joe Kunkel __ R-help@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, rip...@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, UKFax: +44 1865 272595 __ R-help@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.
[R] Unusual slowing of R matrix multiplication version 2.12.1 (2010-10-15) vs 2.12.0
R Version 2.12.1 (2010-10-15) vs 2.12.0 has slowed down 8 fold for dual core and 17 fold for dual-core-dual-processor Macs. I have checked this result on 3 different macs using the following R-script: Using Version 2.12.0 on a dual core dual processor Mac: > source("http://www.bio.umass.edu/biology/kunkel/pub/R/CuriousResult.R";) matrix multiplication 43.543 1.308 14.788 tcrossprod 41.147 1.286 11.9 transposition and reuse40.407 3.525 43.606 elementwise after reshape 21.474 1.828 23.124 columnwise sapply 34.695 32.35 66.592 for loop over columns 37.237 29.471 67.2 On the same day upgrading to 2.12.1 on the same dual core dual processor Mac: > source("http://www.bio.umass.edu/biology/kunkel/pub/R/CuriousResult.R";) matrix multiplication 256.775 2.178 256.919 tcrossprod246.609 1.987 247.075 transposition and reuse39.622 4.602 43.883 elementwise after reshape 21.017 2.343 23.258 columnwise sapply39.393 37.069 75.834 for loop over columns 35.461 33.155 68.165 It seems clear that the upgrade to 2.12.1 has resulted in matrix multiplication using only one core. Notice that the other techniques that avoid matrix multiplication seem to stay the same but the two approaches that use matrix multiply have degraded worse than the expected loss of just 4 fold. Is it possible that a different matrix multiply library was used in changing from version 2.12.0 to 2.12.1? Joe Kunkel __ R-help@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.
[R] "matrix is not of full rank" error in package tgp
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi I want to use the package tgp with its sens() function to cunduct a sensitivity analysis of an ecological simulation model and six independent input parameter. I conducted 10.000 simulations based on a Latin Hypercube design to sample the whole parameter range. Now I want to use the sens function to conduct the sensitivity analysis. I use the following call: SA <- sens(X = X, Z = Z, nn.lhs = 600, model = bgpllm, verb = 2) where X are my 6 input parameter, and Z is the response variable. My problem is, that I get a X[,1:6]-matrix is not of full rank error. I must admit ignorance, as I neither know what a "matrix of full rank" is, and how I can fix this so that I can conduct a sensitivity analysis by using sens(). Any help is appreciated, Thanks, Rainer - -- Rainer M. Krug, PhD (Conservation Ecology, SUN), MSc (Conservation Biology, UCT), Dipl. Phys. (Germany) Centre of Excellence for Invasion Biology Natural Sciences Building Office Suite 2039 Stellenbosch University Main Campus, Merriman Avenue Stellenbosch South Africa Tel:+33 - (0)9 53 10 27 44 Cell: +27 - (0)8 39 47 90 42 Fax (SA): +27 - (0)8 65 16 27 82 Fax (D) : +49 - (0)3 21 21 25 22 44 Fax (FR): +33 - (0)9 58 10 27 44 email: rai...@krugs.de Skype: RMkrug -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAk1P7Q4ACgkQoYgNqgF2egohzgCfYCHjcjsQz/v9KrJAr63etgGZ IdUAn0I1CdV0cLis4a4zqGmHjnm6lzwJ =bFUt -END PGP SIGNATURE- __ R-help@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.
Re: [R] "Matrix' with Functions
Dear all, I would like to thank you for your contribution. I think I got more that one good solutions to work on. Best Regards Alex --- On Thu, 2/3/11, Bert Gunter wrote: From: Bert Gunter Subject: Re: [R] "Matrix' with Functions To: "Samuel Le" Cc: "Alaios" , r-help@r-project.org Date: Thursday, February 3, 2011, 6:32 PM There is no need for eval(parse...) As an another alternative to Rich Heiberger's suggestion, simply define your function as: F <- function(i,a,b,c,d) do.call(paste("f",i,sep=""), list(a,b,c,d)) -- Bert On Thu, Feb 3, 2011 at 9:22 AM, Samuel Le wrote: Hello, Here is a quick suggestion: F<-function(i,j,a,b,c,d) { res<-eval(parse(text=paste("f",i,j,"(a,b,c,d),sep=""))) return(res) } HTH, Samuel -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Alaios Sent: 03 February 2011 16:33 To: R-help@r-project.org Subject: [R] "Matrix' with Functions Dear R members, I have a quite large of function that are named like that f11,f12,...f15 f21,f22,...f25 .. f51,f52,...f52 These are static (hard-coded) functions that the only common they have is that they take the same number and type of input fij(a,b,c,d). As you might understand this is really close to the notion of matrix only that my 'matrix' contains functions. It would be great if I can address all these function using a numbering-scheme like F(i,j) where for example F(1,1) will return the f11(a,b,c,d,). I am sure that this might be quite complex to implement so could you please refer me to some book/tutorial that addresses this kind of topics? I would like to thank you in advance for your help Best Regards Alex __ R-help@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. __ Information from ESET NOD32 Antivirus, version of virus signature database 5843 (20110203) __ The message was checked by ESET NOD32 Antivirus. http://www.eset.com __ Information from ESET NOD32 Antivirus, version of virus signature database 5843 (20110203) __ The message was checked by ESET NOD32 Antivirus. http://www.eset.com __ R-help@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. -- Bert Gunter Genentech Nonclinical Biostatistics 467-7374 http://devo.gene.com/groups/devo/depts/ncb/home.shtml [[alternative HTML version deleted]] __ R-help@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.
Re: [R] "Matrix' with Functions
There is no need for eval(parse...) As an another alternative to Rich Heiberger's suggestion, simply define your function as: F <- function(i,a,b,c,d) do.call(paste("f",i,sep=""), list(a,b,c,d)) -- Bert On Thu, Feb 3, 2011 at 9:22 AM, Samuel Le wrote: > Hello, > > Here is a quick suggestion: > F<-function(i,j,a,b,c,d) > { >res<-eval(parse(text=paste("f",i,j,"(a,b,c,d),sep=""))) >return(res) > } > > HTH, > > Samuel > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of Alaios > Sent: 03 February 2011 16:33 > To: R-help@r-project.org > Subject: [R] "Matrix' with Functions > > Dear R members, > I have a quite large of function that are named like that > f11,f12,...f15 > f21,f22,...f25 > .. > f51,f52,...f52 > > These are static (hard-coded) functions that the only common they have is > that they take the same number and type of input fij(a,b,c,d). As you might > understand this is really close to the notion of matrix only that my > 'matrix' contains functions. It would be great if I can address all these > function using a numbering-scheme like F(i,j) where for example > F(1,1) will return the f11(a,b,c,d,). > > I am sure that this might be quite complex to implement so could you please > refer me to some book/tutorial that addresses this kind of topics? > > I would like to thank you in advance for your help > Best Regards > Alex > > __ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > > > __ Information from ESET NOD32 Antivirus, version of virus > signature database 5843 (20110203) __ > > The message was checked by ESET NOD32 Antivirus. > > http://www.eset.com > > > > __ Information from ESET NOD32 Antivirus, version of virus > signature database 5843 (20110203) __ > > The message was checked by ESET NOD32 Antivirus. > > http://www.eset.com > > __ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > -- Bert Gunter Genentech Nonclinical Biostatistics 467-7374 http://devo.gene.com/groups/devo/depts/ncb/home.shtml [[alternative HTML version deleted]] __ R-help@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.
Re: [R] "Matrix' with Functions
This is very simple. Just put the functions in a list and make the list into a matrix. > f11 <- f12 <- f13 <- f21 <- f22 <- f23 <- function(x) x > F <- list(f11, f12, f13, f21, f22, f23) > F <- matrix(F, byrow=TRUE, 2, 3) > F[[1,1]](4) [1] 4 > Be careful that you get the rows and columns right when you do this with meaningful functions. On Thu, Feb 3, 2011 at 12:22 PM, Samuel Le wrote: > Hello, > > Here is a quick suggestion: > F<-function(i,j,a,b,c,d) > { >res<-eval(parse(text=paste("f",i,j,"(a,b,c,d),sep=""))) >return(res) > } > > HTH, > > Samuel > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of Alaios > Sent: 03 February 2011 16:33 > To: R-help@r-project.org > Subject: [R] "Matrix' with Functions > > Dear R members, > I have a quite large of function that are named like that > f11,f12,...f15 > f21,f22,...f25 > .. > f51,f52,...f52 > > These are static (hard-coded) functions that the only common they have is > that they take the same number and type of input fij(a,b,c,d). As you might > understand this is really close to the notion of matrix only that my > 'matrix' contains functions. It would be great if I can address all these > function using a numbering-scheme like F(i,j) where for example > F(1,1) will return the f11(a,b,c,d,). > > I am sure that this might be quite complex to implement so could you please > refer me to some book/tutorial that addresses this kind of topics? > > I would like to thank you in advance for your help > Best Regards > Alex > > __ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > > > __ Information from ESET NOD32 Antivirus, version of virus > signature database 5843 (20110203) __ > > The message was checked by ESET NOD32 Antivirus. > > http://www.eset.com > > > > __ Information from ESET NOD32 Antivirus, version of virus > signature database 5843 (20110203) __ > > The message was checked by ESET NOD32 Antivirus. > > http://www.eset.com > > __ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] __ R-help@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.
Re: [R] "Matrix' with Functions
Hello, Here is a quick suggestion: F<-function(i,j,a,b,c,d) { res<-eval(parse(text=paste("f",i,j,"(a,b,c,d),sep=""))) return(res) } HTH, Samuel -Original Message- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Alaios Sent: 03 February 2011 16:33 To: R-help@r-project.org Subject: [R] "Matrix' with Functions Dear R members, I have a quite large of function that are named like that f11,f12,...f15 f21,f22,...f25 .. f51,f52,...f52 These are static (hard-coded) functions that the only common they have is that they take the same number and type of input fij(a,b,c,d). As you might understand this is really close to the notion of matrix only that my 'matrix' contains functions. It would be great if I can address all these function using a numbering-scheme like F(i,j) where for example F(1,1) will return the f11(a,b,c,d,). I am sure that this might be quite complex to implement so could you please refer me to some book/tutorial that addresses this kind of topics? I would like to thank you in advance for your help Best Regards Alex __ R-help@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. __ Information from ESET NOD32 Antivirus, version of virus signature database 5843 (20110203) __ The message was checked by ESET NOD32 Antivirus. http://www.eset.com __ Information from ESET NOD32 Antivirus, version of virus signature database 5843 (20110203) __ The message was checked by ESET NOD32 Antivirus. http://www.eset.com __ R-help@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.
Re: [R] "Matrix' with Functions
Seems funny to me: > f <- list (mean, sd, median, sum) > dim (f) <- c (2, 2) or in one line: > f <- structure (.Data=list (mean, sd, median, sum), dim = c(2,2)) > f [,1] [,2] [1,] ?? [2,] ?? > f [1,1] [[1]] function (x, ...) UseMethod("mean") > f [[1,1]] (1:3) [1] 2 > f [[2,1]] (1:3) [1] 1 > f [[1,2]] (1:3) [1] 2 > f [[2,2]] (1:3) [1] 6 HTH Claudia On 02/03/2011 05:33 PM, Alaios wrote: Dear R members, I have a quite large of function that are named like that f11,f12,...f15 f21,f22,...f25 .. f51,f52,...f52 These are static (hard-coded) functions that the only common they have is that they take the same number and type of input fij(a,b,c,d). As you might understand this is really close to the notion of matrix only that my 'matrix' contains functions. It would be great if I can address all these function using a numbering-scheme like F(i,j) where for example F(1,1) will return the f11(a,b,c,d,). I am sure that this might be quite complex to implement so could you please refer me to some book/tutorial that addresses this kind of topics? I would like to thank you in advance for your help Best Regards Alex __ R-help@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. -- Claudia Beleites Dipartimento dei Materiali e delle Risorse Naturali Università degli Studi di Trieste Via Alfonso Valerio 6/a I-34127 Trieste phone: +39 0 40 5 58-37 68 email: cbelei...@units.it __ R-help@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.
[R] "Matrix' with Functions
Dear R members, I have a quite large of function that are named like that f11,f12,...f15 f21,f22,...f25 .. f51,f52,...f52 These are static (hard-coded) functions that the only common they have is that they take the same number and type of input fij(a,b,c,d). As you might understand this is really close to the notion of matrix only that my 'matrix' contains functions. It would be great if I can address all these function using a numbering-scheme like F(i,j) where for example F(1,1) will return the f11(a,b,c,d,). I am sure that this might be quite complex to implement so could you please refer me to some book/tutorial that addresses this kind of topics? I would like to thank you in advance for your help Best Regards Alex __ R-help@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.
Re: [R] matrix and a function - apply function
there is no need for 'apply' here, because R can handle vectors. ord<-m[,1]+m[,2]/m[,1] Am 02.02.2011 15:12, schrieb ADias: > > Hi > > I have this function and this matrix: > > function(x,y) x+y/x > > m<-matrix(c(1,2,4,2,10,8),3,2) > >> m > [,1] [,2] > [1,]12 > [2,]2 10 > [3,]48 > > each row represent a point (x,y) in a chart and I want via my fucntion to > calculate the image in order to get this results: > > for point (1,2) I would get 1+2/1 = 3 > for point (2,10) I would get 2+10/2 = 7 > for point (4,8) I would get 4+8/4 = 6 > > I have tried using sapply here but I get this: > >> sapply(m,function(x,y) x+y/x) > Error in y/x : 'y' is missing > > what I am doing wrong? > > thanks > ADias -- Eik Vettorazzi Institut für Medizinische Biometrie und Epidemiologie Universitätsklinikum Hamburg-Eppendorf Martinistr. 52 20246 Hamburg T ++49/40/7410-58243 F ++49/40/7410-57790 __ R-help@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.
Re: [R] matrix and a function - apply function
Hi r-help-boun...@r-project.org napsal dne 02.02.2011 16:05:21: > > On Feb 2, 2011, at 9:12 AM, ADias wrote: > > > > > Hi > > > > I have this function and this matrix: > > > > function(x,y) x+y/x > > > > m<-matrix(c(1,2,4,2,10,8),3,2) > > > >> m > > [,1] [,2] > > [1,]12 > > [2,]2 10 > > [3,]48 > > > > each row represent a point (x,y) in a chart and I want via my > > fucntion to > > calculate the image in order to get this results: > > > > for point (1,2) I would get 1+2/1 = 3 > > for point (2,10) I would get 2+10/2 = 7 > > for point (4,8) I would get 4+8/4 = 6 > > > > I have tried using sapply here but I get this: > > > >> sapply(m,function(x,y) x+y/x) > > Error in y/x : 'y' is missing > > I'm not sure what sapply does with a matrix argument. I've only used t > with vectors and lists. I suspect that it would straighten out the > argument to a length = 6 vector. (And then, of course, the "y" > wouldn't be there.) > > > > > > what I am doing wrong? > > Two things: instead use apply() and realize that the argument is > passed as a vector > > apply(m, 1, function(x) x[1] +x[2]/x[1] ) Maybe apply is not necessary here > m[,1]+m[,2]/m[,1] [1] 3 7 6 Regards Petr > > > -- > David Winsemius, MD > West Hartford, CT > > __ > R-help@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. __ R-help@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.
Re: [R] matrix and a function - apply function
On Feb 2, 2011, at 9:12 AM, ADias wrote: Hi I have this function and this matrix: function(x,y) x+y/x m<-matrix(c(1,2,4,2,10,8),3,2) m [,1] [,2] [1,]12 [2,]2 10 [3,]48 each row represent a point (x,y) in a chart and I want via my fucntion to calculate the image in order to get this results: for point (1,2) I would get 1+2/1 = 3 for point (2,10) I would get 2+10/2 = 7 for point (4,8) I would get 4+8/4 = 6 I have tried using sapply here but I get this: sapply(m,function(x,y) x+y/x) Error in y/x : 'y' is missing I'm not sure what sapply does with a matrix argument. I've only used t with vectors and lists. I suspect that it would straighten out the argument to a length = 6 vector. (And then, of course, the "y" wouldn't be there.) what I am doing wrong? Two things: instead use apply() and realize that the argument is passed as a vector apply(m, 1, function(x) x[1] +x[2]/x[1] ) -- David Winsemius, MD West Hartford, CT __ R-help@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.
[R] matrix and a function - apply function
Hi I have this function and this matrix: function(x,y) x+y/x m<-matrix(c(1,2,4,2,10,8),3,2) > m [,1] [,2] [1,]12 [2,]2 10 [3,]48 each row represent a point (x,y) in a chart and I want via my fucntion to calculate the image in order to get this results: for point (1,2) I would get 1+2/1 = 3 for point (2,10) I would get 2+10/2 = 7 for point (4,8) I would get 4+8/4 = 6 I have tried using sapply here but I get this: > sapply(m,function(x,y) x+y/x) Error in y/x : 'y' is missing what I am doing wrong? thanks ADias -- View this message in context: http://r.789695.n4.nabble.com/matrix-and-a-function-apply-function-tp3254271p3254271.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] MAtrix addressing
On Jan 26, 2011, at 2:47 AM, Alaios wrote: The reason is the following image http://img545.imageshack.us/i/maptoregion.jpg/ In the picture above you will find the indexes for each cell. Also you will see that I place that matrix inside a x,y region that spans from -1 to 1. I am trying to write one function that will get as argument a (x,y) value x e[-1,1] y e[-1,1] and will return the indexes of that cell tha x,y value correspond to. I really do not have a clue how I should try to approach that to solve it. So based on some version I had for 1-d vector I tried to extend it for 2-d. I used findInterval as a core to get results. Unfortunately my code fails to produce accurate results as my approach 'assumes' (this is something inhereted by the find Interval function) that the numbering starts bottom left and goes high top right. You will find my code below If one wants to take an ordinary r matrix and reorder it in the manner you describe: mtx2 <- mtx[ nrow(mtx):1, ] Whether that is an efficient way to get at the sokution your you programming task I cannot say. It sounds as though it has gotten too convoluted. I was not able to comprehend the overall goal from your problem description. sr.map <- function(sr){ # This function converts the s(x,y) matrix into a function x that spans #from -1 to 1 and y spans from -1 to 1. # Input: sr a x,y matrix containing the shadowing values of a Region breaksX <- seq(from=-1, to = 1, length = nrow(sr) +1L ) breaksY <- seq(from=-1, to = 1, length = ncol(sr) + 1L) function(x,y){ # SPAGGETI CODE FOR EVER indx <- findInterval(x, breaksX,rightmost.closed=TRUE) indy <- findInterval(y, breaksY,rightmost.closed=TRUE) c(indx,indy) } } sr<-matrix(data=seq(from=1,to=36),nrow=6,ncol=6,byrow=TRUE) f.sr.map<-sr.map((sr)) f.sr.map(-0.1,-0.1) f.sr.map(0.1,0.1) Best Regards Alex --- On Wed, 1/26/11, David Winsemius wrote: From: David Winsemius Subject: Re: [R] MAtrix addressing To: "Alaios" Cc: R-help@r-project.org Date: Wednesday, January 26, 2011, 2:54 AM On Jan 25, 2011, at 4:50 PM, Alaios wrote: Hello I would like to ask you if it is possible In R Cran to change the default way of addressing a matrix. for example matrix(data=seq(from=1,to=4,nrow=2,ncol=2, by row numbering) # not having R at this pc will create something like the following 1 2 3 4 the way R address this matrix is from top left corner moving to bottom right. The cell numbers in that way are 1 2 3 4 IS it possible to change this default addresing number to something that goes bottom left to top right? In this simple case I want to have 3 4 1 2 Would that be possible? Yes. it's possible but ... why? I would like to thank y for your help Regards Alex __ R-help@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. David Winsemius, MD West Hartford, CT David Winsemius, MD West Hartford, CT __ R-help@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.
Re: [R] MAtrix addressing
The reason is the following image http://img545.imageshack.us/i/maptoregion.jpg/ In the picture above you will find the indexes for each cell. Also you will see that I place that matrix inside a x,y region that spans from -1 to 1. I am trying to write one function that will get as argument a (x,y) value x e[-1,1] y e[-1,1] and will return the indexes of that cell tha x,y value correspond to. I really do not have a clue how I should try to approach that to solve it. So based on some version I had for 1-d vector I tried to extend it for 2-d. I used findInterval as a core to get results. Unfortunately my code fails to produce accurate results as my approach 'assumes' (this is something inhereted by the find Interval function) that the numbering starts bottom left and goes high top right. You will find my code below sr.map <- function(sr){ # This function converts the s(x,y) matrix into a function x that spans #from -1 to 1 and y spans from -1 to 1. # Input: sr a x,y matrix containing the shadowing values of a Region breaksX <- seq(from=-1, to = 1, length = nrow(sr) +1L ) breaksY <- seq(from=-1, to = 1, length = ncol(sr) + 1L) function(x,y){ # SPAGGETI CODE FOR EVER indx <- findInterval(x, breaksX,rightmost.closed=TRUE) indy <- findInterval(y, breaksY,rightmost.closed=TRUE) c(indx,indy) } } sr<-matrix(data=seq(from=1,to=36),nrow=6,ncol=6,byrow=TRUE) f.sr.map<-sr.map((sr)) f.sr.map(-0.1,-0.1) f.sr.map(0.1,0.1) Best Regards Alex --- On Wed, 1/26/11, David Winsemius wrote: > From: David Winsemius > Subject: Re: [R] MAtrix addressing > To: "Alaios" > Cc: R-help@r-project.org > Date: Wednesday, January 26, 2011, 2:54 AM > > On Jan 25, 2011, at 4:50 PM, Alaios wrote: > > > Hello > > I would like to ask you if it is possible In R Cran to > change the default way of addressing a matrix. > > for example > > matrix(data=seq(from=1,to=4,nrow=2,ncol=2, by row > numbering) # not having R at this pc > > > > will create something like the following > > 1 2 > > 3 4 > > > > the way R address this matrix is from top left corner > moving to bottom right. > > The cell numbers in that way are > > 1 2 > > 3 4 > > > > IS it possible to change this default addresing number > to something that goes bottom left to top right? In this > simple case I want to have > > 3 4 > > 1 2 > > > > Would that be possible? > > Yes. it's possible but ... why? > > > > > I would like to thank y for your help > > Regards > > Alex > > > > __ > > R-help@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. > > David Winsemius, MD > West Hartford, CT > > __ R-help@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.
Re: [R] MAtrix addressing
On Jan 25, 2011, at 4:50 PM, Alaios wrote: Hello I would like to ask you if it is possible In R Cran to change the default way of addressing a matrix. for example matrix(data=seq(from=1,to=4,nrow=2,ncol=2, by row numbering) # not having R at this pc will create something like the following 1 2 3 4 the way R address this matrix is from top left corner moving to bottom right. The cell numbers in that way are 1 2 3 4 IS it possible to change this default addresing number to something that goes bottom left to top right? In this simple case I want to have 3 4 1 2 Would that be possible? Yes. it's possible but ... why? I would like to thank y for your help Regards Alex __ R-help@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. David Winsemius, MD West Hartford, CT __ R-help@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.
[R] MAtrix addressing
Hello I would like to ask you if it is possible In R Cran to change the default way of addressing a matrix. for example matrix(data=seq(from=1,to=4,nrow=2,ncol=2, by row numbering) # not having R at this pc will create something like the following 1 2 3 4 the way R address this matrix is from top left corner moving to bottom right. The cell numbers in that way are 1 2 3 4 IS it possible to change this default addresing number to something that goes bottom left to top right? In this simple case I want to have 3 4 1 2 Would that be possible? I would like to thank y for your help Regards Alex __ R-help@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.
Re: [R] matrix manipulations
On Mon, Jan 17, 2011 at 10:37:42PM +, Monica Pisica wrote: > > Hi, > > I've got 2 very good solutions, thank you very much. One, from Henrique > Dallazuanna using the library reshape and one line of code - although it will > take me quite some time to understand it. Here it is what he sent: > > library(reshape) > xtabs(rowSums(cbind(value.x, value.y), na.rm = TRUE) ~ X1 + X2, > merge(melt(m1), melt(m2), by = c('X1', 'X2'), all = TRUE), exclude = FALSE) > > > The other is from Phil Spector ( code below) that i can understand quite > easily, although until now to my shame i never quite used factor levels and > their properties and i don't know their uses and possibilities. Until now i > tried to avoid them and transform them in something else (like character > strings). Let me add a comment on factors. Character vectors are easier to manipulate and factors carry additional information. A balance between their uses depends on the application. A possible strategy is to use character vectors, when the sequence of categorical data should be manipulated, and convert to a factor, when needed. There is an R Wiki page with some tips concerning factors at http://rwiki.sciviews.org/doku.php?id=tips:data-factors:factors Petr Savicky. __ R-help@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.
Re: [R] matrix manipulations
Hi, I've got 2 very good solutions, thank you very much. One, from Henrique Dallazuanna using the library reshape and one line of code - although it will take me quite some time to understand it. Here it is what he sent: library(reshape) xtabs(rowSums(cbind(value.x, value.y), na.rm = TRUE) ~ X1 + X2, merge(melt(m1), melt(m2), by = c('X1', 'X2'), all = TRUE), exclude = FALSE) The other is from Phil Spector ( code below) that i can understand quite easily, although until now to my shame i never quite used factor levels and their properties and i don't know their uses and possibilities. Until now i tried to avoid them and transform them in something else (like character strings). Again, thanks for all your help, Monica > Date: Mon, 17 Jan 2011 12:13:09 -0800 > From: spec...@stat.berkeley.edu > To: pisican...@hotmail.com > CC: r-help@r-project.org > Subject: Re: [R] matrix manipulations > > Monica - > Perhaps this small example can demonstrate how factors can > solve your problem: > > > d1 = > > data.frame(cat=sample(c('cat2','cat5','cat6'),100,replace=TRUE),group=sample(c('land','water'),100,replace=TRUE)) > > d2 = > > data.frame(cat=sample(c('cat1','cat3','cat4'),100,replace=TRUE),group=sample(c('land','water'),100,replace=TRUE)) > > d1$cat = factor(d1$cat,levels=c('cat1','cat2','cat3','cat4','cat5','cat6')) > > d2$cat = factor(d2$cat,levels=c('cat1','cat2','cat3','cat4','cat5','cat6')) > > table(d1$group,d1$cat) + table(d2$group,d2$cat) > > cat1 cat2 cat3 cat4 cat5 cat6 > land 14 17 18 22 19 23 > water 19 15 16 11 10 16 > > This works because when you include all possible levels in a factor, R will > automatically put zeroes in the right places when you use table(): > > > table(d1$group,d1$cat) > cat1 cat2 cat3 cat4 cat5 cat6 > land 0 17 0 0 19 23 > water 0 15 0 0 10 16 > > table(d2$group,d2$cat) > cat1 cat2 cat3 cat4 cat5 cat6 > land 14 0 18 22 0 0 > water 19 0 16 11 0 0 > > Hope this helps. > - Phil Spector > Statistical Computing Facility > Department of Statistics > UC Berkeley > spec...@stat.berkeley.edu > > > > On Mon, 17 Jan 2011, Monica Pisica wrote: > > > > > Hi, > > > > I am having some difficulties with matrix operations. It is a little hard > > to explain it so please bear with me. I have a very large data set, large > > enough that it needs to be split in parts in order to deal with. I can work > > things on these "parts" but the problem lies in adding together these parts > > for the final answer. > > > > So that been said, let's say that i split the data in 2 parts, 1 and 2. > > Each part has data belonging to 6 different categories, and each category > > has 2 different classes, these classes being the same for each category. > > The classes are called "land" and "water" and each category is labeled > > "cat1" to "cat6". I am using the command (function) table to tabulate each > > class for each category, but since i split the data in 2 parts, one part > > has only some of the 6 categories, and the other some other of the 6 > > categories (and not necessarily exclusive). > > > > So let's built some results after i used the table function. > > > > m1 <- matrix(c(32, 35, 36, 12, 15, 16), nrow = 2, ncol = 3, byrow = TRUE, > > dimnames = list(c("land", "water"), c("cat2", "cat5", "cat6"))) > > > >> m1 > > cat2 cat5 cat6 > > land 32 35 36 > > water 12 15 16 > > > > m2 <- matrix(c(45, 46, 47, 48, 21, 22, 23, 24), nrow = 2, ncol = 4, byrow = > > TRUE, dimnames = list(c("land", "water"), c("cat1", "cat2", "cat3", > > "cat4"))) > > > >> m2 > > cat1 cat2 cat3 cat4 > > land 45 46 47 48 > > water 21 22 23 24 > > > > So my end desired result should be a matrix (or a data frame) that has 6 > > columns called cat1 to cat6 and 2 rows labeled land and water, and for the > > category that appears in both m1 and m2 the end result will be a sum. > > > > results will be m3: > > > > cat1 cat2 cat3 cat4 cat5 cat6 > > land 45 78 47 48 35 36 > > water 21 34 23 24 15 16 > > > > To do this i thought in making an empty matrix for each m1 and m2 (called > > m01 and m02 r
Re: [R] matrix manipulations
Try this: library(reshape) xtabs(rowSums(cbind(value.x, value.y), na.rm = TRUE) ~ X1 + X2, merge(melt(m1), melt(m2), by = c('X1', 'X2'), all = TRUE), exclude = FALSE) On Mon, Jan 17, 2011 at 5:59 PM, Monica Pisica wrote: > > Hi, > > I am having some difficulties with matrix operations. It is a little hard > to explain it so please bear with me. I have a very large data set, large > enough that it needs to be split in parts in order to deal with. I can work > things on these "parts" but the problem lies in adding together these parts > for the final answer. > > So that been said, let's say that i split the data in 2 parts, 1 and 2. > Each part has data belonging to 6 different categories, and each category > has 2 different classes, these classes being the same for each category. The > classes are called "land" and "water" and each category is labeled "cat1" to > "cat6". I am using the command (function) table to tabulate each class for > each category, but since i split the data in 2 parts, one part has only some > of the 6 categories, and the other some other of the 6 categories (and not > necessarily exclusive). > > So let's built some results after i used the table function. > > m1 <- matrix(c(32, 35, 36, 12, 15, 16), nrow = 2, ncol = 3, byrow = TRUE, > dimnames = list(c("land", "water"), c("cat2", "cat5", "cat6"))) > > > m1 > cat2 cat5 cat6 > land 3235 36 > water 12 15 16 > > m2 <- matrix(c(45, 46, 47, 48, 21, 22, 23, 24), nrow = 2, ncol = 4, byrow = > TRUE, dimnames = list(c("land", "water"), c("cat1", "cat2", "cat3", > "cat4"))) > > > m2 > cat1 cat2 cat3 cat4 > land 45 46 47 48 > water 21 22 23 24 > > So my end desired result should be a matrix (or a data frame) that has 6 > columns called cat1 to cat6 and 2 rows labeled land and water, and for the > category that appears in both m1 and m2 the end result will be a sum. > > results will be m3: > > cat1 cat2 cat3 cat4 cat5 cat6 > land 45 78 4748 35 36 > water 21 34 2324 15 16 > > To do this i thought in making an empty matrix for each m1 and m2 (called > m01 and m02 respectively) with 6 columns and 2 rows, and do a long if else > statement in which i match the name of the first column in m1 with the name > of the first column in m01 and if they match get the data from m1, if not > leave it 0 and so on. Same thing for m2 and m02. This is long and extremely > clunky but afterwards i can add m01 with m02 and get my desired result m3. > Is there any way i can do this more elegantly? My real data is split in 4 > parts, but the problem is the same. > > Thanks for all your inputs, and sorry for this long email, but i didn't > know how else i could explain what i wanted to do. > > Monica > __ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix manipulations
Monica - Perhaps this small example can demonstrate how factors can solve your problem: d1 = data.frame(cat=sample(c('cat2','cat5','cat6'),100,replace=TRUE),group=sample(c('land','water'),100,replace=TRUE)) d2 = data.frame(cat=sample(c('cat1','cat3','cat4'),100,replace=TRUE),group=sample(c('land','water'),100,replace=TRUE)) d1$cat = factor(d1$cat,levels=c('cat1','cat2','cat3','cat4','cat5','cat6')) d2$cat = factor(d2$cat,levels=c('cat1','cat2','cat3','cat4','cat5','cat6')) table(d1$group,d1$cat) + table(d2$group,d2$cat) cat1 cat2 cat3 cat4 cat5 cat6 land14 17 18 22 19 23 water 19 15 16 11 10 16 This works because when you include all possible levels in a factor, R will automatically put zeroes in the right places when you use table(): table(d1$group,d1$cat) cat1 cat2 cat3 cat4 cat5 cat6 land 0 1700 19 23 water0 1500 10 16 table(d2$group,d2$cat) cat1 cat2 cat3 cat4 cat5 cat6 land140 18 2200 water 190 16 1100 Hope this helps. - Phil Spector Statistical Computing Facility Department of Statistics UC Berkeley spec...@stat.berkeley.edu On Mon, 17 Jan 2011, Monica Pisica wrote: Hi, I am having some difficulties with matrix operations. It is a little hard to explain it so please bear with me. I have a very large data set, large enough that it needs to be split in parts in order to deal with. I can work things on these "parts" but the problem lies in adding together these parts for the final answer. So that been said, let's say that i split the data in 2 parts, 1 and 2. Each part has data belonging to 6 different categories, and each category has 2 different classes, these classes being the same for each category. The classes are called "land" and "water" and each category is labeled "cat1" to "cat6". I am using the command (function) table to tabulate each class for each category, but since i split the data in 2 parts, one part has only some of the 6 categories, and the other some other of the 6 categories (and not necessarily exclusive). So let's built some results after i used the table function. m1 <- matrix(c(32, 35, 36, 12, 15, 16), nrow = 2, ncol = 3, byrow = TRUE, dimnames = list(c("land", "water"), c("cat2", "cat5", "cat6"))) m1 cat2 cat5 cat6 land 3235 36 water 12 15 16 m2 <- matrix(c(45, 46, 47, 48, 21, 22, 23, 24), nrow = 2, ncol = 4, byrow = TRUE, dimnames = list(c("land", "water"), c("cat1", "cat2", "cat3", "cat4"))) m2 cat1 cat2 cat3 cat4 land 45 46 47 48 water 21 22 23 24 So my end desired result should be a matrix (or a data frame) that has 6 columns called cat1 to cat6 and 2 rows labeled land and water, and for the category that appears in both m1 and m2 the end result will be a sum. results will be m3: cat1 cat2 cat3 cat4 cat5 cat6 land 45 78 4748 35 36 water 21 34 2324 15 16 To do this i thought in making an empty matrix for each m1 and m2 (called m01 and m02 respectively) with 6 columns and 2 rows, and do a long if else statement in which i match the name of the first column in m1 with the name of the first column in m01 and if they match get the data from m1, if not leave it 0 and so on. Same thing for m2 and m02. This is long and extremely clunky but afterwards i can add m01 with m02 and get my desired result m3. Is there any way i can do this more elegantly? My real data is split in 4 parts, but the problem is the same. Thanks for all your inputs, and sorry for this long email, but i didn't know how else i could explain what i wanted to do. Monica __ R-help@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. __ R-help@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.
[R] matrix manipulations
Hi, I am having some difficulties with matrix operations. It is a little hard to explain it so please bear with me. I have a very large data set, large enough that it needs to be split in parts in order to deal with. I can work things on these "parts" but the problem lies in adding together these parts for the final answer. So that been said, let's say that i split the data in 2 parts, 1 and 2. Each part has data belonging to 6 different categories, and each category has 2 different classes, these classes being the same for each category. The classes are called "land" and "water" and each category is labeled "cat1" to "cat6". I am using the command (function) table to tabulate each class for each category, but since i split the data in 2 parts, one part has only some of the 6 categories, and the other some other of the 6 categories (and not necessarily exclusive). So let's built some results after i used the table function. m1 <- matrix(c(32, 35, 36, 12, 15, 16), nrow = 2, ncol = 3, byrow = TRUE, dimnames = list(c("land", "water"), c("cat2", "cat5", "cat6"))) > m1 cat2 cat5 cat6 land 3235 36 water 12 15 16 m2 <- matrix(c(45, 46, 47, 48, 21, 22, 23, 24), nrow = 2, ncol = 4, byrow = TRUE, dimnames = list(c("land", "water"), c("cat1", "cat2", "cat3", "cat4"))) > m2 cat1 cat2 cat3 cat4 land 45 46 47 48 water 21 22 23 24 So my end desired result should be a matrix (or a data frame) that has 6 columns called cat1 to cat6 and 2 rows labeled land and water, and for the category that appears in both m1 and m2 the end result will be a sum. results will be m3: cat1 cat2 cat3 cat4 cat5 cat6 land 45 78 4748 35 36 water 21 34 2324 15 16 To do this i thought in making an empty matrix for each m1 and m2 (called m01 and m02 respectively) with 6 columns and 2 rows, and do a long if else statement in which i match the name of the first column in m1 with the name of the first column in m01 and if they match get the data from m1, if not leave it 0 and so on. Same thing for m2 and m02. This is long and extremely clunky but afterwards i can add m01 with m02 and get my desired result m3. Is there any way i can do this more elegantly? My real data is split in 4 parts, but the problem is the same. Thanks for all your inputs, and sorry for this long email, but i didn't know how else i could explain what i wanted to do. Monica __ R-help@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.
Re: [R] matrix looping accessing previous column
Using which() improves my code, but now I'm receiving some data.frame error and still does not convert the values to negative. #TAKE PART OF MATRIX CEM1_PARTIAL <- CEM1[1:10,1:10] #CEM1_PARTIAL=apply(CEM1_PARTIAL,2,as.character) #CEM1_PARTIAL <- as.numeric(as.character(CEM1_PARTIAL)) #CEM1_PARTIAL[which(CEM1_PARTIAL$V4 == "DOWN") - 1] <- CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - 1] * -1 for(j in 1:ncol(CEM1_PARTIAL)) { for(i in 1:nrow(CEM1_PARTIAL)) { CEM1_PARTIAL[which(CEM1_PARTIAL[i,j] == "DOWN")] = CEM1_PARTIAL[which(CEM1_PARTIAL[i,j] == "DOWN")-1] * -1 } } Error in data.frame(value, row.names = rn, check.names = FALSE, check.rows = FALSE) : row names supplied are of the wrong length -- View this message in context: http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165380.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix looping accessing previous column
That just converts my values in V3 to NA -- View this message in context: http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165340.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix looping accessing previous column
Convert your column to numeric: CEM1_PARTIAL$V3 <- as.numeric(as.character(CEM1_PARTIAL$V3)) On Mon, Dec 27, 2010 at 4:28 PM, R_novice wrote: > > Thank you for the quick response :-). I've applied your suggestion to my > code, but I still receive an error: > > > CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - 1] <- > > CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - 1] * -1 > Warning message: > In Ops.factor(CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - : > * not meaningful for factors > > I would like to perform this evaluation in a loop b/c my data matrix > actually contains 109 columns, and 32,000 rows. > > More suggestions are appreciated! > > Thanks! > -- > View this message in context: > http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165325.html > Sent from the R help mailing list archive at Nabble.com. > > __ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix looping accessing previous column
Thank you for the quick response :-). I've applied your suggestion to my code, but I still receive an error: > CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - 1] <- > CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - 1] * -1 Warning message: In Ops.factor(CEM1_PARTIAL$V3[which(CEM1_PARTIAL$V4 == "DOWN") - : * not meaningful for factors I would like to perform this evaluation in a loop b/c my data matrix actually contains 109 columns, and 32,000 rows. More suggestions are appreciated! Thanks! -- View this message in context: http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165325.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix looping accessing previous column
Try this: > x V1 V2 V3 V4 1 PROBE 1 2.5 UP 2 PROBE 2 1.0 UP 3 PROBE 3 1.4 DOWN 4 PROBE 4 2.0 UP 5 PROBE 5 1.3 DOWN x$V3[which(x$V4 == "DOWN") - 1] <- x$V3[which(x$V4 == "DOWN") - 1] * -1 On Mon, Dec 27, 2010 at 4:11 PM, R_novice wrote: > > Hi, > > I have a matrix with numbers and character. I want to evaluate each cell > and > change the value of the cell before it depending on the evaluation. My > evaluation: if a cell had the word "down" change the cell preceding it to a > negative number by multiplying that value by a -1. I am have trouble going > back on clumn to make this change. I'm receiving an error on the j-1 part, > and the "down" cells are converted to 'NA'. > A sample of my data matrix and code are pasted below. Any suggestions would > be appreciated. Thanks! > > Data: > > PROBE 1 2.5 UP > PROBE 2 1UP > PROBE 3 1.4 DOWN > PROBE 4 2.0 UP > PROBE 5 1.3 DOWN > > #TAKE PART OF MATRIX > CEM1_PARTIAL <- CEM1[1:3,1:5] > > for(j in 1:ncol(CEM1_PARTIAL)) > { >for(i in 1:nrow(CEM1_PARTIAL)) >{ > if(CEM1_PARTIAL[i,j] == "down") > {CEM1_PARTIAL[i,j-1]= CEM1_PARTIAL[i,j-1] * -1;} >} > } > > error: > Warning messages: > 1: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > 2: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > 3: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > 4: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > 5: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > 6: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : > * not meaningful for factors > > -- > View this message in context: > http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165308.html > Sent from the R help mailing list archive at Nabble.com. > > __ > R-help@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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]] __ R-help@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.
[R] matrix looping accessing previous column
Hi, I have a matrix with numbers and character. I want to evaluate each cell and change the value of the cell before it depending on the evaluation. My evaluation: if a cell had the word "down" change the cell preceding it to a negative number by multiplying that value by a -1. I am have trouble going back on clumn to make this change. I'm receiving an error on the j-1 part, and the "down" cells are converted to 'NA'. A sample of my data matrix and code are pasted below. Any suggestions would be appreciated. Thanks! Data: PROBE 1 2.5 UP PROBE 2 1UP PROBE 3 1.4 DOWN PROBE 4 2.0 UP PROBE 5 1.3 DOWN #TAKE PART OF MATRIX CEM1_PARTIAL <- CEM1[1:3,1:5] for(j in 1:ncol(CEM1_PARTIAL)) { for(i in 1:nrow(CEM1_PARTIAL)) { if(CEM1_PARTIAL[i,j] == "down") {CEM1_PARTIAL[i,j-1]= CEM1_PARTIAL[i,j-1] * -1;} } } error: Warning messages: 1: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors 2: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors 3: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors 4: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors 5: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors 6: In Ops.factor(CEM1_PARTIAL[i, j - 1], -1) : * not meaningful for factors -- View this message in context: http://r.789695.n4.nabble.com/matrix-looping-accessing-previous-column-tp3165308p3165308.html Sent from the R help mailing list archive at Nabble.com. __ R-help@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.
Re: [R] matrix indexing in 'for' loop?
Thank you all once again .. Yeah, its working now. -- Regards, Mahalakshmi Graduate Student #20, Department of Geography Michigan State University East Lansing, MI 48824 Quoting Liviu Andronic : > On Wed, Dec 22, 2010 at 6:39 PM, wrote: >> Thank you both for your suggestions. I have another question - is there a >> specific way to access the individual elements of a 'list' variable? i.e. >> >> dmi = matrix(rnorm(20),4,5) >> soi = matrix(rnorm(20),4,5) >> pe = matrix(rnorm(20),4,5) >> y <- list(dmi, soi, pe) >> >> y[[1]]  gives >> [,1]      [,2]      [,3]      [,4]      [,5] >> [1,] -0.54463900 1.6732445 -0.3807847 -1.0460530 -0.8142748 >> [2,] -0.49654004 -0.9634258 0.9074139 -0.1576030 -1.2268558 >> [3,] -1.61835766 -0.4240122 0.3626670 0.7182964 0.1576446 >> [4,] -0.06313983 0.6743465 -1.9897107 0.8027337 -1.4372131 >> >> But, I am interested in accessing the 1st column of 'dmi' matrix here - not >> as dmi[,1] but in terms of 'y'. Is it possible with 'list' function or >> something else? >> > > Is this what you need? >> y[[1]] >      [,1]    [,2]    [,3]    [,4]   >[,5] > [1,] 0.2523449 -1.26606999 0.27594223 -0.5158524 -0.599899 > [2,] -1.9155409 0.01081565 0.44497873 0.1819517 1.187899 > [3,] 0.7624774 0.31296468 -0.02187076 0.9389091 0.865527 > [4,] -0.8082626 -1.44330148 1.32975075 0.1788399 1.204917 > >> y[[1]][,1] > [1] 0.2523449 -1.9155409 0.7624774 -0.8082626 > > Liviu > [[alternative HTML version deleted]] __ R-help@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.
Re: [R] matrix indexing in 'for' loop?
Have you consulted R's extensive documentation? -- in particular, "An Introduction to R," which would seem like an obvious place for R newbies to start. If you had done so, you would have found your question answered there in section 6.1 on lists. -- Bert Gunter On Wed, Dec 22, 2010 at 9:39 AM, wrote: > > > Thank you both for your suggestions. I have another question - is there a > specific way to access the individual elements of a 'list' variable? i.e. > > dmi = matrix(rnorm(20),4,5) > soi = matrix(rnorm(20),4,5) > pe = matrix(rnorm(20),4,5) > y <- list(dmi, soi, pe) > > y[[1]] gives > [,1] [,2] [,3] [,4] [,5] > [1,] -0.54463900 1.6732445 -0.3807847 -1.0460530 -0.8142748 > [2,] -0.49654004 -0.9634258 0.9074139 -0.1576030 -1.2268558 > [3,] -1.61835766 -0.4240122 0.3626670 0.7182964 0.1576446 > [4,] -0.06313983 0.6743465 -1.9897107 0.8027337 -1.4372131 > > But, I am interested in accessing the 1st column of 'dmi' matrix here - not > as dmi[,1] but in terms of 'y'. Is it possible with 'list' function or > something else? > > Thanks again. > > -- > Regards, > Maha > Graduate Student > Department of Geography > Michigan State University > Quoting Liviu Andronic : > >> On Wed, Dec 22, 2010 at 2:57 AM, Phil Spector >> wrote: >>> To make your loop work, you need to learn about the get function. >>> I'm not going to give you the details because there are better >>> approaches available. >>> First, let's make some data that will give values which can be verified. >>> (All the correlations of the data you created >>> are exactly equal to 1.) And to make the code readable, I'll >>> omit the ts.m prefix. >>> set.seed(14) dmi = matrix(rnorm(20),4,5) soi = matrix(rnorm(20),4,5) pe = matrix(rnorm(20),4,5) allmats = list(dmi,soi,pe) >>> >>> Since cor.test won't automatically do the tests for all columns >>> of a matrix, I'll write a little helper function: >>> gettests = function(x)apply(x,2,function(col)cor.test(pe[,2],col) tests = lapply(allmats,gettests) >>> >>> Now tests is a list of length 2, with a list of the output from >>> cor.test for the five columns of the each matrix with pe[,2] >>> (Notice that in your program you made no provision to store the results >>> anywhere.) >>> >>> Suppose you want the correlations: >>> sapply(tests,function(x)sapply(x,function(test)test$estimate)) >>> >>> [,1] [,2] >>> cor 0.12723615 0.1342751 >>> cor 0.07067819 0.6228158 >>> cor -0.28761533 0.6218661 >>> cor 0.83731828 -0.9602551 >>> cor -0.36050836 0.1170035 >>> >>> The probabilities for the tests can be found similarly: >>> sapply(tests,function(x)sapply(x,function(test)test$p.value)) >>> >>> [,1] [,2] >>> [1,] 0.8727638 0.86572490 >>> [2,] 0.9293218 0.37718416 >>> [3,] 0.7123847 0.37813388 >>> [4,] 0.1626817 0.03974489 >>> [5,] 0.6394916 0.88299648 >>> >> Hmisc already provides a function for doing this, rcorr(). Try to >> compute correlations using Rcmdr for an example. >> >> Regards >> Liviu >> >> >>> (Take a look at the "Values" section in the help file for cor.test >>> to get the names of other quantities of interest.) >>> >>> The main advantage to this approach is that if you add more matrices >>> to the allmats list, the other steps automaticall take it into account. >>> >>> Hope this helps. >>> - Phil Spector >>> Statistical Computing Facility >>> Department of Statistics >>> UC Berkeley >>> spec...@stat.berkeley.edu >>> >>> >>> >>> >>> >>> On Tue, 21 Dec 2010, govin...@msu.edu wrote: >>> Hi, I am having trouble with matrices. I?have 2 matrices as given below, and I am interested in using these matrices inside "for" loops used to calculate correlations. I am creating a list with the names of the matrices assuming this list could be indexed inside the 'for' loop to retrieve the matrix values. But, as expected the code throws out an error. Can someone suggest a better way to call these matrices inside the loops? ts.m.dmi <- matrix(c(1:20), 4, 5) ts.m.soi <- matrix(c(21:40), 4, 5) ts.m.pe <- matrix(c(21:40), 4, 5) factors <- c("ts.m.dmi", "ts.m.soi") for (j in 0:1){ y <- factors[j+1] for (i in 1:5){ cor.pe.y <- cor(ts.m.pe[,2], y[,i]) ct.tst <- cor.test(ts.m.pe[,2], y[,i]) } } Thanks for your time. -- Regards, Maha Graduate Student [[alternative HTML version deleted]] >>> >>> __ >>> R-help@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, minim
Re: [R] matrix indexing in 'for' loop?
On Wed, Dec 22, 2010 at 6:39 PM, wrote: > Thank you both for your suggestions. I have another question - is there a > specific way to access the individual elements of a 'list' variable? i.e. > > dmi = matrix(rnorm(20),4,5) > soi = matrix(rnorm(20),4,5) > pe = matrix(rnorm(20),4,5) > y <- list(dmi, soi, pe) > > y[[1]] gives > [,1] [,2] [,3] [,4] [,5] > [1,] -0.54463900 1.6732445 -0.3807847 -1.0460530 -0.8142748 > [2,] -0.49654004 -0.9634258 0.9074139 -0.1576030 -1.2268558 > [3,] -1.61835766 -0.4240122 0.3626670 0.7182964 0.1576446 > [4,] -0.06313983 0.6743465 -1.9897107 0.8027337 -1.4372131 > > But, I am interested in accessing the 1st column of 'dmi' matrix here - not > as dmi[,1] but in terms of 'y'. Is it possible with 'list' function or > something else? > Is this what you need? > y[[1]] [,1][,2][,3] [,4] [,5] [1,] 0.2523449 -1.26606999 0.27594223 -0.5158524 -0.599899 [2,] -1.9155409 0.01081565 0.44497873 0.1819517 1.187899 [3,] 0.7624774 0.31296468 -0.02187076 0.9389091 0.865527 [4,] -0.8082626 -1.44330148 1.32975075 0.1788399 1.204917 > y[[1]][,1] [1] 0.2523449 -1.9155409 0.7624774 -0.8082626 Liviu __ R-help@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.
Re: [R] matrix indexing in 'for' loop?
Thank you both for your suggestions. I have another question - is there a specific way to access the individual elements of a 'list' variable? i.e. dmi = matrix(rnorm(20),4,5) soi = matrix(rnorm(20),4,5) pe = matrix(rnorm(20),4,5) y <- list(dmi, soi, pe) y[[1]]  gives [,1]      [,2]      [,3]      [,4]      [,5] [1,] -0.54463900 1.6732445 -0.3807847 -1.0460530 -0.8142748 [2,] -0.49654004 -0.9634258 0.9074139 -0.1576030 -1.2268558 [3,] -1.61835766 -0.4240122 0.3626670 0.7182964 0.1576446 [4,] -0.06313983 0.6743465 -1.9897107 0.8027337 -1.4372131 But, I am interested in accessing the 1st column of 'dmi' matrix here - not as dmi[,1] but in terms of 'y'. Is it possible with 'list' function or something else? Thanks again. -- Regards, Maha Graduate Student Department of Geography Michigan State University Quoting Liviu Andronic : > On Wed, Dec 22, 2010 at 2:57 AM, Phil Spector > wrote: >> To make your loop work, you need to learn about the get function. >> I'm not going to give you the details because there are better >> approaches available. >> First, let's make some data that will give values which can be verified. >>  (All the correlations of the data you created >> are exactly equal to 1.)  And to make the code readable, I'll >> omit the ts.m prefix. >> >>> set.seed(14) >>> dmi = matrix(rnorm(20),4,5) >>> soi = matrix(rnorm(20),4,5) >>> pe = matrix(rnorm(20),4,5) >>> allmats = list(dmi,soi,pe) >> >> Since cor.test won't automatically do the tests for all columns >> of a matrix, I'll write a little helper function: >> >>> gettests = function(x)apply(x,2,function(col)cor.test(pe[,2],col) >>> tests = lapply(allmats,gettests) >> >> Now tests is a list of length 2, with a list of the output from >> cor.test for the five columns of the each matrix with pe[,2] >> (Notice that in your program you made no provision to store the results >> anywhere.) >> >> Suppose you want the correlations: >> >>> sapply(tests,function(x)sapply(x,function(test)test$estimate)) >> >>      [,1]    [,2] >> cor  0.12723615  0.1342751 >> cor  0.07067819  0.6228158 >> cor -0.28761533  0.6218661 >> cor  0.83731828 -0.9602551 >> cor -0.36050836  0.1170035 >> >> The probabilities for the tests can be found similarly: >> >>> sapply(tests,function(x)sapply(x,function(test)test$p.value)) >> >>      [,1]    [,2] >> [1,] 0.8727638 0.86572490 >> [2,] 0.9293218 0.37718416 >> [3,] 0.7123847 0.37813388 >> [4,] 0.1626817 0.03974489 >> [5,] 0.6394916 0.88299648 >> > Hmisc already provides a function for doing this, rcorr(). Try to > compute correlations using Rcmdr for an example. > > Regards > Liviu > > >> (Take a look at the "Values" section in the help file for cor.test >> to get the names of other quantities of interest.) >> >> The main advantage to this approach is that if you add more matrices >> to the allmats list, the other steps automaticall take it into account. >> >> Hope this helps. >>                     - Phil Spector >>                     Statistical >> Computing Facility >>                     Department of >> Statistics >>                     UC Berkeley >>                     >> spec...@stat.berkeley.edu >> >> >> >> >> >> On Tue, 21 Dec 2010, govin...@msu.edu wrote: >> >>> >>> >>> Hi, >>> >>> I am having trouble with matrices. I?have 2 matrices as given below, and I >>> am interested in using these matrices inside "for" loops used to calculate >>> correlations. I am creating a list with the names of the matrices assuming >>> this list could be indexed inside the 'for' loop to retrieve the matrix >>> values. But, as expected the code throws out an error. Can someone >>> suggest a >>> better way to call these matrices inside the loops? >>> >>> ts.m.dmi <- matrix(c(1:20), 4, 5) >>> ts.m.soi <- matrix(c(21:40), 4, 5) >>> ts.m.pe <- matrix(c(21:40), 4, 5) >>> >>> factors <- c("ts.m.dmi", "ts.m.soi") >>> for (j in 0:1){ >>> y <- factors[j+1] >>> >>> for (i in 1:5){ >>> >>> cor.pe.y <- cor(ts.m.pe[,2], y[,i]) >>> ct.tst <- cor.test(ts.m.pe[,2], y[,i]) >>> } >>> } >>> >>> Thanks for your time. >>> >>> -- >>> Regards, >>> Maha >>> Graduate Student >>>     [[alternative HTML version deleted]] >>> >>> >> >> __ >> R-help@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. >> > > > > -- > Do you know how to read? > http://www.alienetworks.com/srtest.cfm > http://goodies.xfce.org/projects/applications/xfce4-dict#speed-reader > Do you know how to write? > http://garbl.home.comcast.net/~garbl/stylemanual/e.htm#e-mail > [[a
Re: [R] matrix indexing in 'for' loop?
On Wed, Dec 22, 2010 at 2:57 AM, Phil Spector wrote: > To make your loop work, you need to learn about the get function. > I'm not going to give you the details because there are better > approaches available. > First, let's make some data that will give values which can be verified. > (All the correlations of the data you created > are exactly equal to 1.) And to make the code readable, I'll > omit the ts.m prefix. > >> set.seed(14) >> dmi = matrix(rnorm(20),4,5) >> soi = matrix(rnorm(20),4,5) >> pe = matrix(rnorm(20),4,5) >> allmats = list(dmi,soi,pe) > > Since cor.test won't automatically do the tests for all columns > of a matrix, I'll write a little helper function: > >> gettests = function(x)apply(x,2,function(col)cor.test(pe[,2],col) >> tests = lapply(allmats,gettests) > > Now tests is a list of length 2, with a list of the output from > cor.test for the five columns of the each matrix with pe[,2] > (Notice that in your program you made no provision to store the results > anywhere.) > > Suppose you want the correlations: > >> sapply(tests,function(x)sapply(x,function(test)test$estimate)) > > [,1] [,2] > cor 0.12723615 0.1342751 > cor 0.07067819 0.6228158 > cor -0.28761533 0.6218661 > cor 0.83731828 -0.9602551 > cor -0.36050836 0.1170035 > > The probabilities for the tests can be found similarly: > >> sapply(tests,function(x)sapply(x,function(test)test$p.value)) > > [,1] [,2] > [1,] 0.8727638 0.86572490 > [2,] 0.9293218 0.37718416 > [3,] 0.7123847 0.37813388 > [4,] 0.1626817 0.03974489 > [5,] 0.6394916 0.88299648 > Hmisc already provides a function for doing this, rcorr(). Try to compute correlations using Rcmdr for an example. Regards Liviu > (Take a look at the "Values" section in the help file for cor.test > to get the names of other quantities of interest.) > > The main advantage to this approach is that if you add more matrices > to the allmats list, the other steps automaticall take it into account. > > Hope this helps. > - Phil Spector > Statistical Computing Facility > Department of Statistics > UC Berkeley > spec...@stat.berkeley.edu > > > > > > On Tue, 21 Dec 2010, govin...@msu.edu wrote: > >> >> >> Hi, >> >> I am having trouble with matrices. I?have 2 matrices as given below, and I >> am interested in using these matrices inside "for" loops used to calculate >> correlations. I am creating a list with the names of the matrices assuming >> this list could be indexed inside the 'for' loop to retrieve the matrix >> values. But, as expected the code throws out an error. Can someone suggest a >> better way to call these matrices inside the loops? >> >> ts.m.dmi <- matrix(c(1:20), 4, 5) >> ts.m.soi <- matrix(c(21:40), 4, 5) >> ts.m.pe <- matrix(c(21:40), 4, 5) >> >> factors <- c("ts.m.dmi", "ts.m.soi") >> for (j in 0:1){ >> y <- factors[j+1] >> >> for (i in 1:5){ >> >> cor.pe.y <- cor(ts.m.pe[,2], y[,i]) >> ct.tst <- cor.test(ts.m.pe[,2], y[,i]) >> } >> } >> >> Thanks for your time. >> >> -- >> Regards, >> Maha >> Graduate Student >> [[alternative HTML version deleted]] >> >> > > __ > R-help@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. > -- Do you know how to read? http://www.alienetworks.com/srtest.cfm http://goodies.xfce.org/projects/applications/xfce4-dict#speed-reader Do you know how to write? http://garbl.home.comcast.net/~garbl/stylemanual/e.htm#e-mail __ R-help@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.