Re: [R] generate a list as follows: 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, . . . . ., n, n, n, n
In '?rep' find out about the 'each' argument. Also there is the function 'gl' which creates a factor and offers a shorter syntax for your problem. If n equals 5 use one of: rep(seq(5), each = 4) gl(5,4) On 19 April 2015 at 15:44, John Sorkin wrote: > Windows 7 64-bit > R 3.1.3 > RStudio 0.98.1103 > > > I am trying to generate a list of length 4n which consists of the > integers 1 to n repeated in groups of four, i.e. > > 1,1,1,1, 2,2,2,2, 3,3,3,3, . . . . , n,n,n,n > > (The spaces in the list are added only for clarity.) > > I can generate the list as follows, but the code must be modified for any > value n, and the code is UGLY! > > c(rep(1,4), rep(2,4), rep(3,4), . . . ,c(n,4)) > > Can anyone help me? > > Thank you, > John > > John David Sorkin M.D., Ph.D. > Professor of Medicine > Chief, Biostatistics and Informatics > University of Maryland School of Medicine Division of Gerontology and > Geriatric Medicine > Baltimore VA Medical Center > 10 North Greene Street > GRECC (BT/18/GR) > Baltimore, MD 21201-1524 > (Phone) 410-605-7119410-605-7119 > (Fax) 410-605-7913 (Please call phone number above prior to faxing) > > > Call > Send SMS > Add to Skype > You'll need Skype CreditFree via Skype > > John David Sorkin M.D., Ph.D. > Professor of Medicine > Chief, Biostatistics and Informatics > University of Maryland School of Medicine Division of Gerontology and > Geriatric Medicine > Baltimore VA Medical Center > 10 North Greene Street > GRECC (BT/18/GR) > Baltimore, MD 21201-1524 > (Phone) 410-605-7119410-605-7119 > (Fax) 410-605-7913 (Please call phone number above prior to faxing) > > > > > John David Sorkin M.D., Ph.D. > Professor of Medicine > Chief, Biostatistics and Informatics > University of Maryland School of Medicine Division of Gerontology and > Geriatric Medicine > Baltimore VA Medical Center > 10 North Greene Street > GRECC (BT/18/GR) > Baltimore, MD 21201-1524 > (Phone) 410-605-7119 > (Fax) 410-605-7913 (Please call phone number above prior to faxing) > > > Confidentiality Statement: > This email message, including any attachments, is for ...{{dropped:16}} __ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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] regexpr - ignore all special characters and punctuation in a string
Hi Dimitri, str_replace_all is not in the base libraries, you could use 'gsub' as well, for example: a = "What a nice day today! - Story of happiness: Part 2." b = "What a nice day today: Story of happiness (Part 2)" sa = gsub("[^A-Za-z0-9]", "", a) sb = gsub("[^A-Za-z0-9]", "", b) a==b # [1] FALSE sa==sb # [1] TRUE Take care of the extra space in a after the '-', so also replace spaces... Best, Sven. On 20 April 2015 at 16:05, Dimitri Liakhovitski < dimitri.liakhovit...@gmail.com> wrote: > I think I found a partial answer: > > str_replace_all(x, "[[:punct:]]", " ") > > On Mon, Apr 20, 2015 at 9:59 AM, Dimitri Liakhovitski > wrote: > > Hello! > > > > Please point me in the right direction. > > I need to match 2 strings, but focusing ONLY on characters, ignoring > > all special characters and punctuation signs, including (), "", etc.. > > > > For example: > > I want the following to return: TRUE > > > > "What a nice day today! - Story of happiness: Part 2." == > >"What a nice day today: Story of happiness (Part 2)" > > > > > > -- > > Thank you! > > Dimitri Liakhovitski > > > > -- > Dimitri Liakhovitski > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] rename and color a list of list of list of values
Hi Karim, you should learn ?Map to iterate along the list and supply mutliple list arguments (there is also parallel:::mcMap for multicore). The magic of the color code generation you figure out yourself, I guess... Here 'i' intends to be the value, 'n' the name, e.g. # returns color by character/numeric value: magic_colour <- function (x) { ... } # returns child list_child <- function (i, n) { list(name=n, colour=magic_colour(i)) } # returns parent list_parent <- function (i, n) { list(name=n, children=Map(list_child, i, names(i)), colour=magic_colour(n)) } # get grandparent grandparent <- Map(list_parent, expBefore, names(expBefore)) Hope this helps! Best, S. On 5 June 2015 at 18:31, Karim Mezhoud wrote: > Hi all, > I have a list like this > > expBefore <- > > list(HM450=list(brac_tcga=list("ATM"=0.19,"ATR"=0.02,"BRCA1"=0.02,"BRCA2"=0.89,"CHEK1"=0.71,"CHEK2"=0.03), > > > gbm_tcga=list("ATM"=0.19,"ATR"=0.02,"BRCA1"=0.02,"BRCA2"=0.89,"CHEK1"=0.71,"CHEK2"=0.03) > ), > > > HM27=list(brac_tcga=list("ATM"=0.19,"ATR"=0.02,"BRCA1"=0.02,"BRCA2"=0.89,"CHEK1"=0.71,"CHEK2"=0.03), > > > gbm_tcga=list("ATM"=0.19,"ATR"=0.02,"BRCA1"=0.02,"BRCA2"=0.89,"CHEK1"=0.71,"CHEK2"=0.03) > ) > ) > > > and I would convert it to > > expAfter <-list( > list( > name="HM450", > children=list( > list(name="brca_tcga", >children=list( > list(name="ATM", colour="11"), > list(name="ATR", colour="33"), > list(name="BRCA1", colour="55"), > list(name="BRCA2", colour="77"), > list(name="CHEK1", colour="99"), > list(name="CHEK2", colour="bb") > >), colour="aa" # brca_tcga >), > list(name="gbm_tcga", > children=list( > list(name="ATM", colour="001100"), > list(name="ATR", colour="003300"), > list(name="BRCA1", colour="005500"), > list(name="BRCA2", colour="007700"), > list(name="CHEK1", colour="009900"), > list(name="CHEK2", colour="00bb00") > ), colour="345345" # gbm_tcga > ) > >), colour="ffa500" # HM450 > ), > list( > name="HM27", > children=list( > list(name="brca_tcga", >children=list( > list(name="ATM", colour="11"), > list(name="ATR", colour="33"), > list(name="BRCA1", colour="55"), > list(name="BRCA2", colour="77"), > list(name="CHEK1", colour="99"), > list(name="CHEK2", colour="bb") > >), colour="aa" ##brca_tcga >), > list(name="gbm_tcga", >children=list( > list(name="ATM", colour="001100"), > list(name="ATR", colour="003300"), > list(name="BRCA1", colour="005500"), > list(name="BRCA2", colour="007700"), > list(name="CHEK1", colour="009900"), > list(name="CHEK2", colour="00bb00") >), colour="345345") #gbm_tcga > > ), colour="ff00ff" #HM27 > ) > > ); > any suggestion? > Thanks > > [[alternative HTML version deleted]] > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] Make 2nd col of 2-col df into header row of same df then adjust col1 data display
Another solution: CaseID <- c("1015285", "1005317", "1012281", "1015285", "1015285", "1007183", "1008833", "1015315", "1015322", "1015285") Primary.Viol.Type <- c("AS.Age", "HS.Hours", "HS.Hours", "HS.Hours", "RK.Records_CL", "OT.Overtime", "OT.Overtime", "OT.Overtime", "V.Poster_Other", "V.Poster_Other") library(reshape2) dcast(data.frame(CaseID, Primary.Viol.Type), CaseID~Primary.Viol.Type, length) # result: Using Primary.Viol.Type as value column: use value.var to override. CaseID AS.Age HS.Hours OT.Overtime RK.Records_CL V.Poster_Other 1 1005317 01 0 0 0 2 1007183 00 1 0 0 3 1008833 00 1 0 0 4 1012281 01 0 0 0 5 1015285 11 0 1 1 6 1015315 00 1 0 0 7 1015322 00 0 0 1 best, s. On 19 December 2014 at 06:35, Chel Hee Lee wrote: > Please take a look at my code again. The error message says that object > 'Primary.Viol.Type' not found. Have you ever created the object > 'Primary.Viol.Type'? It will be working if you replace 'Primary.Viol.Type' > by 'PViol.Type.Per.Case.Original$Primary.Viol.Type' where 'factor()' is > used. I hope this helps. > > Chel Hee Lee > > On 12/18/2014 08:57 PM, Crombie, Burnette N wrote: >> >> Chel, your solution is fantastic on the dataset I submitted in my question >> but it is not working when I import my real dataset into R. Do I need to >> vectorize the columns in my real dataset after importing? I tried a few >> things (###) but not making progress: >> >> MERGE_PViol.Detail.Per.Case <- >> read.csv("~/FOIA_FLSA/MERGE_PViol.Detail.Per.Case_for_rtf10.csv", >> stringsAsFactors=TRUE) >> >> ### select only certain columns >> PViol.Type.Per.Case.Original <- MERGE_PViol.Detail.Per.Case[,c("CaseID", >> "Primary.Viol.Type")] >> >> ### write.csv(PViol.Type.Per.Case,file="PViol.Type.Per.Case.Select.csv") >> ### PViol.Type.Per.Case.Original <- >> read.csv("~/FOIA_FLSA/PViol.Type.Per.Case.Select.csv") >> ### PViol.Type.Per.Case.Original$X <- NULL >> ###PViol.Type.Per.Case.Original[] <- lapply(PViol.Type.Per.Case.Original, >> as.character) >> >> PViol.Type <- c("CaseID", >> "BW.BackWages", >> "LD.Liquid_Damages", >> "MW.Minimum_Wage", >> "OT.Overtime", >> "RK.Records_FLSA", >> "V.Poster_Other", >> "AS.Age", >> "BW.WHMIS_BackWages", >> "HS.Hours", >> "OA.HazOccupationAg", >> "ON.HazOccupationNonAg", >> "R3.Reg3AgeOccupation", >> "RK.Records_CL", >> "V.Other") >> >> PViol.Type.Per.Case.Original$Primary.Viol.Type <- >> factor(Primary.Viol.Type, levels=PViol.Type, labels=PViol.Type) >> >> ### Error in factor(Primary.Viol.Type, levels = PViol.Type, labels = >> PViol.Type) : object 'Primary.Viol.Type' not found >> >> tmp <- >> split(PViol.Type.Per.Case.Original,PViol.Type.Per.Case.Original$CaseID) >> ans <- ifelse(do.call(rbind, lapply(tmp, >> function(x)table(x$Primary.Viol.Type))), 1, NA) >> >> >> >> -Original Message- >> From: Crombie, Burnette N >> Sent: Thursday, December 18, 2014 3:01 PM >> To: 'Chel Hee Lee' >> Subject: RE: [R] Make 2nd col of 2-col df into header row of same df then >> adjust col1 data display >> >> Thanks for taking the time to review this, Chel. I've got to step away >> from my desk, but will reply more substantially as soon as possible. -- BNC >> >> -Original Message- >> From: Chel Hee Lee [mailto:chl...@mail.usask.ca] >> Sent: Thursday, December 18, 2014 2:43 PM >> To: Jeff Newmiller; Crombie, Burnette N >> Cc: r-help@r-project.org >> Subject: Re: [R] Make 2nd col of 2-col df into header row of same df then >> adjust col1 data display >> >> I like the approach presented by Jeff Newmiller as shown in the previous >> post (I really like his way). As he suggested, it would be good to start >> with 'factor' since you have all values of 'Primary.Viol.Type'. >> You may try to use 'split()' function for creating table that you wish to >> build. Please see the below (I hope this helps): >> >> > PViol.Type.Per.Case.Original$Primary.Viol.Type <- >> factor(Primary.Viol.Type, levels=PViol.Type, labels=PViol.Type) > > tmp <- >> split(PViol.Type.Per.Case.Original, >> PViol.Type.Per.Case.Original$CaseID) >> > ans <- ifelse(do.call(rbind, lapply(tmp, function(x) >> table(x$Primary.Viol.Type))), 1, NA) > ans >> CaseID BW.BackWages LD.Liquid_Damages MW.Minimum_Wage >> OT.Overtime >> 1005317 NA NANA NA NA >> 1007183 NA NANA NA 1 >> 1008833 NA NA
Re: [R] Sum function and missing values --- need to mimic SAS sum function
you can also define 'na.rm' in sum() by 'NA state' of x (where x is your vector holding the data): sum(x, na.rm=!all(is.na(x))) On 26 January 2015 at 13:45, Martin Maechler wrote: >> Jim Lemon >> on Mon, 26 Jan 2015 11:21:03 +1100 writes: > > > Hi Allen, How about this: > > > sum_w_NA<-function(x) ifelse(all(is.na(x)),NA,sum(x,na.rm=TRUE)) > > Excuse, Jim, but that's yet another "horrible misuse of ifelse()" > > John Fox's reply *did* contain the "proper" solution > > if (all(is.na(x))) NA else sum(x, na.rm=TRUE) > > The ifelse() function should never be used in such cases. > Read more after googling > > "Do NOT use ifelse()" > > -- include the quotes in your search -- > > or directly at >http://stat.ethz.ch/pipermail/r-help/2014-December/424367.html > > Yes, this has been on R-help a month ago.. > Martin > > > On Mon, Jan 26, 2015 at 10:21 AM, Allen Bingham > > wrote: > >> I understand that in order to get the sum function to > >> ignore missing values I need to supply the argument > >> na.rm=TRUE. However, when summing numeric values in which > >> ALL components are "NA" ... the result is 0.0 ... instead > >> of (what I would get from SAS) of NA (or in the case of > >> SAS "."). > >> > >> Accordingly, I've had to go to 'extreme' measures to get > >> the sum function to result in NA if all arguments are > >> missing (otherwise give me a sum of all non-NA elements). > >> > >> So for example here's a snippet of code that ALMOST does > >> what I want: > >> > >> > >> > SumValue<-apply(subset(InputDataFrame,!is.na(Variable.1)|!is.na(Variable.2), > >> select=c(Variable.1,Variable.2)),1,sum,na.rm=TRUE) > >> > >> In reality this does NOT give me records with NA for > >> SumValue ... but it doesn't give me values for any > >> records in which both Variable.1 and Variable.2 are NA > >> --- which is "good enough" for my purposes. > >> > >> I'm guessing with a little more work I could come up with > >> a way to adapt the code above so that I could get it to > >> work like SAS's sum function ... > >> > >> ... but before I go that extra mile I thought I'd ask > >> others if they know of functions in either base R ... or > >> in a package that will better mimic the SAS sum function. > >> > >> Any suggestions? > >> > >> Thanks. __ Allen > >> Bingham aebingh...@gmail.com > >> > >> __ > >> R-help@r-project.org mailing list -- To UNSUBSCRIBE and > >> more, see 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 -- To UNSUBSCRIBE and > > more, see 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 -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] Sum function and missing values --- need to mimic SAS sum function
Maybe this is due to the usage of rep() in ifelse(): f.rep <- function(ans){ans <- rep(ans,1);return(ans)} f <- function(ans){return(ans)} f(a <- 123) # no print here f.rep(a <- 123) # prints: # [1] 123 On 27 January 2015 at 11:54, Bert Gunter wrote: > Huh?? > >> ifelse(TRUE, a <- 2L, a <- 3L) > [1] 2 >> a > [1] 2 > > Please clarify. > > -- Bert > > Bert Gunter > Genentech Nonclinical Biostatistics > (650) 467-7374 > > "Data is not information. Information is not knowledge. And knowledge > is certainly not wisdom." > Clifford Stoll > > > > > On Mon, Jan 26, 2015 at 2:22 PM, Hervé Pagès wrote: >> Hi Martin, >> >> On 01/26/2015 04:45 AM, Martin Maechler wrote: Jim Lemon on Mon, 26 Jan 2015 11:21:03 +1100 writes: >>> >>> >>> > Hi Allen, How about this: >>> >>> > sum_w_NA<-function(x) ifelse(all(is.na(x)),NA,sum(x,na.rm=TRUE)) >>> >>> Excuse, Jim, but that's yet another "horrible misuse of ifelse()" >>> >>> John Fox's reply *did* contain the "proper" solution >>> >>> if (all(is.na(x))) NA else sum(x, na.rm=TRUE) >>> >>> The ifelse() function should never be used in such cases. >>> Read more after googling >>> >>> "Do NOT use ifelse()" >>> >>> -- include the quotes in your search -- >>> >>> or directly at >>> http://stat.ethz.ch/pipermail/r-help/2014-December/424367.html >> >> >> Interesting. You could have added the following item to your list: >> >> 4. less likely to play strange tricks on you: >> >> > ifelse(TRUE, a <- 2L, a <- 3L) >> [1] 2 >> > a >> [1] 3 >> >> Yeah I've seen people using ifelse() that way and being totally >> confused... >> >> Cheers, >> H. >> >>> >>> Yes, this has been on R-help a month ago.. >>> Martin >>> >>> > On Mon, Jan 26, 2015 at 10:21 AM, Allen Bingham >>> > wrote: >>> >> I understand that in order to get the sum function to >>> >> ignore missing values I need to supply the argument >>> >> na.rm=TRUE. However, when summing numeric values in which >>> >> ALL components are "NA" ... the result is 0.0 ... instead >>> >> of (what I would get from SAS) of NA (or in the case of >>> >> SAS "."). >>> >> >>> >> Accordingly, I've had to go to 'extreme' measures to get >>> >> the sum function to result in NA if all arguments are >>> >> missing (otherwise give me a sum of all non-NA elements). >>> >> >>> >> So for example here's a snippet of code that ALMOST does >>> >> what I want: >>> >> >>> >> >>> >> >>> SumValue<-apply(subset(InputDataFrame,!is.na(Variable.1)|!is.na(Variable.2), >>> >> select=c(Variable.1,Variable.2)),1,sum,na.rm=TRUE) >>> >> >>> >> In reality this does NOT give me records with NA for >>> >> SumValue ... but it doesn't give me values for any >>> >> records in which both Variable.1 and Variable.2 are NA >>> >> --- which is "good enough" for my purposes. >>> >> >>> >> I'm guessing with a little more work I could come up with >>> >> a way to adapt the code above so that I could get it to >>> >> work like SAS's sum function ... >>> >> >>> >> ... but before I go that extra mile I thought I'd ask >>> >> others if they know of functions in either base R ... or >>> >> in a package that will better mimic the SAS sum function. >>> >> >>> >> Any suggestions? >>> >> >>> >> Thanks. __ Allen >>> >> Bingham aebingh...@gmail.com >>> >> >>> >> __ >>> >> R-help@r-project.org mailing list -- To UNSUBSCRIBE and >>> >> more, see 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 -- To UNSUBSCRIBE and >>> > more, see 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 -- To UNSUBSCRIBE and more, see >>> 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. >>> >> >> -- >> Hervé Pagès >> >> Program in Computational Biology >> Division of Public Health Sciences >> Fred Hutchinson Cancer Research Center >> 1100 Fairview Ave. N, M1-B514 >> P.O. Box 19024 >> Seattle, WA 98109-1024 >> >> E-mail: hpa...@fredhutch.org >> Phone: (206) 667-5791 >> Fax:(206) 667-1319 >> >> __ >> R-help@r-project.org
Re: [R] Extract data from Array to Table
Make use of the plyr and reshape2 package (both on CRAN): library(plyr) d<-adply(ArrayDiseaseCor, 1:2) # adply calls function identity by default d<-melt(d) d<-subset(d,value>.5) head(d) You will have to rename columns, or adjust arguments in melt/adply. Note: use set.seed before sampling for reproducible code! Best, S. On 11 February 2015 at 17:11, Karim Mezhoud wrote: > Dear All, > I am facing the task to extract data from array to table. here an example > of array. > > ##Get A list of Matrices with unequal rows > > Disease <- NULL > Diseases <- NULL > ListMatByGene <- NULL > for(i in 1:3){ > > Disease[[i]] <-matrix(sample(-30:30,25+(5* > i)),5+i) > rownames(Disease[[i]]) <- paste0("Sample",1:(5+i)) > colnames(Disease[[i]]) <- paste0("Gene",1:5) > > D <- paste0("Disease",i) > Diseases[[D]] <- Disease[[i]] > } > > > ## get the same Column from all matrices > getColumn <- function(x, colNum, len = nrow(x)){ > y <- x[,colNum] > length(y) <- len > y > } > > ## get Matrices by the same columns of the list of matrices > getMatrices <- function(colNums, dataList = x){ > # the number of rows required > n <- max(sapply(dataList, nrow)) > lapply(colNums, function(x, dat, n) { # iterate along requested columns > do.call(cbind, lapply(dat, getColumn,x, len=n)) # iterate along > input data list > }, dataList, n) > } > > ## Rotate the list of matrices by 90° > G <- paste0("Gene",1:5) > ListMatByGene[G] <- getMatrices(c(1:ncol(Diseases[[1]])),dataList=Diseases) > > ## get Disease correlation by gene > DiseaseCorrelation <- lapply(ListMatByGene,function(x) cor(x,use="na", > method="spearman")) > > ##convert the list of Matrices to array > ArrayDiseaseCor <- array(unlist(DiseaseCorrelation), dim = > c(nrow(DiseaseCorrelation[[1]]), ncol(DiseaseCorrelation[[1]]), > length(DiseaseCorrelation))) > dimnames(ArrayDiseaseCor) <- list(names(Diseases), names(Diseases), > colnames(Diseases[[1]])) > > ## Select only correlation bigger than 0.5 from the array > FilterDiseaseCor <- apply(ArrayDiseaseCor,MARGIN=c(1,2) ,function(x) > x[abs(x)>0.5]) > > ## Final result > FilterDiseaseCor > > Disease1 Disease2 Disease3 > Disease1 Numeric,5 Numeric,2 -0.9428571 > Disease2 Numeric,2 Numeric,5 Numeric,2 > Disease3 -0.9428571 Numeric,2 Numeric,5 > > > Question is: > How can get a table as: > > D1 D2 Cor Gene > Disease1Disease2 -0.94Gene2 > Disease1Disease2 0.78Gene4 > Disease3Disease2 0.5 Gene5 > ... > > and > Disease1 Disease2 Disease3 > Disease1510 > Disease21 53 > Disease30 3 5 > > Or in general, How can I extract data from Array to Table? > > Thanks > Karim > > [[alternative HTML version deleted]] > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] Extract data from Array to Table
see inline On 12 February 2015 at 09:10, Sven E. Templer wrote: > Make use of the plyr and reshape2 package (both on CRAN): > I forgot: library(reshape2) > library(plyr) > d<-adply(ArrayDiseaseCor, 1:2) > # adply calls function identity by default > d<-melt(d) > d<-subset(d,value>.5) > head(d) > > You will have to rename columns, or adjust arguments in melt/adply. > Note: use set.seed before sampling for reproducible code! > > Best, S. > > On 11 February 2015 at 17:11, Karim Mezhoud wrote: >> Dear All, >> I am facing the task to extract data from array to table. here an example >> of array. >> >> ##Get A list of Matrices with unequal rows >> >> Disease <- NULL >> Diseases <- NULL >> ListMatByGene <- NULL >> for(i in 1:3){ >> >> Disease[[i]] <-matrix(sample(-30:30,25+(5* >> i)),5+i) >> rownames(Disease[[i]]) <- paste0("Sample",1:(5+i)) >> colnames(Disease[[i]]) <- paste0("Gene",1:5) >> >> D <- paste0("Disease",i) >> Diseases[[D]] <- Disease[[i]] >> } >> >> >> ## get the same Column from all matrices >> getColumn <- function(x, colNum, len = nrow(x)){ >> y <- x[,colNum] >> length(y) <- len >> y >> } >> >> ## get Matrices by the same columns of the list of matrices >> getMatrices <- function(colNums, dataList = x){ >> # the number of rows required >> n <- max(sapply(dataList, nrow)) >> lapply(colNums, function(x, dat, n) { # iterate along requested columns >> do.call(cbind, lapply(dat, getColumn,x, len=n)) # iterate along >> input data list >> }, dataList, n) >> } >> >> ## Rotate the list of matrices by 90° >> G <- paste0("Gene",1:5) >> ListMatByGene[G] <- getMatrices(c(1:ncol(Diseases[[1]])),dataList=Diseases) >> >> ## get Disease correlation by gene >> DiseaseCorrelation <- lapply(ListMatByGene,function(x) cor(x,use="na", >> method="spearman")) >> >> ##convert the list of Matrices to array >> ArrayDiseaseCor <- array(unlist(DiseaseCorrelation), dim = >> c(nrow(DiseaseCorrelation[[1]]), ncol(DiseaseCorrelation[[1]]), >> length(DiseaseCorrelation))) >> dimnames(ArrayDiseaseCor) <- list(names(Diseases), names(Diseases), >> colnames(Diseases[[1]])) >> >> ## Select only correlation bigger than 0.5 from the array >> FilterDiseaseCor <- apply(ArrayDiseaseCor,MARGIN=c(1,2) ,function(x) >> x[abs(x)>0.5]) >> >> ## Final result >> FilterDiseaseCor >> >> Disease1 Disease2 Disease3 >> Disease1 Numeric,5 Numeric,2 -0.9428571 >> Disease2 Numeric,2 Numeric,5 Numeric,2 >> Disease3 -0.9428571 Numeric,2 Numeric,5 >> >> >> Question is: >> How can get a table as: >> >> D1 D2 Cor Gene >> Disease1Disease2 -0.94Gene2 >> Disease1Disease2 0.78Gene4 >> Disease3Disease2 0.5 Gene5 >> ... >> >> and >> Disease1 Disease2 Disease3 >> Disease1510 >> Disease21 53 >> Disease30 3 5 >> >> Or in general, How can I extract data from Array to Table? >> >> Thanks >> Karim >> >> [[alternative HTML version deleted]] >> >> __ >> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see >> 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 -- To UNSUBSCRIBE and more, see 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] Raster Help
Without (example) code it is hard to follow... use ?dput to present some data (subset). But if it is data.frames you are dealing with (for sure with read.csv, but not so sure at all with raster maps), give this a try: ?merge On 19 February 2015 at 17:44, Simon Tarr wrote: > Hello everyone, > > I need a little help with some R syntax to complete what (I think) is a > fairly straightforward task- hopefully someone can assist! > > I have a raster map of the UK which is split into postcode areas (e.g. DE, > NG, NR etc. 127 postcodes in total). > > I have installed the package 'raster' and have successfully plotted the > .img in R. All working and looks correct with the raster. > > I also have a comma delimited CSV file containing the same postcodes as the > raster with another column next to it containing revenue for each postcode. > > *I was wondering if someone could help me merge/bind the revenue figures > into the correct postcode in the raster so that I can plot revenue per > postcode.* > > I feel I should be using cbind and reclassify to do this but I can't be > sure. > > Any help would be appreciated. Thanks in advance! > > Simon > > [[alternative HTML version deleted]] > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] Comparing each component of vector to each component of a Matrix.
Hi, you didn't specify values in A, and you first wanted to compare bi with Aij, but then also which bi is less/equal to zero. For the first case, with A <- matrix(0:3,2) b <- seq(-1,5) and a comparison function for bi less/equal to Aij like f <- function (bi) {as.integer(bi<=A)} you can iterate along b with lapply(b, f) # contains results as matrices in a list, each with same dimensions as A sapply(b, f) # aligns results to an length(A)*length(b) matrix Best, S. On 11 March 2015 at 08:01, Frederic Ntirenganya wrote: > Hi All, > > I need a help on a loop which can compare the each component of vector to > each component of a Matrix. > > Let a vector b = {b1, b2, ...,bn} and 2x2 matrix A = Aij. > > I need to compare each component of the vector with each component of a > matrix and print 1 if the component is less or equal to one and print 0 > otherwise. > > bi <= Aij, print 1 and 0 otherwise. > > Any help is appreciated. > > Regards, > Frederic. > > > Frederic Ntirenganya > Maseno University, > African Maths Initiative, > Kenya. > Mobile:(+254)718492836 > Email: fr...@aims.ac.za > https://sites.google.com/a/aims.ac.za/fredo/ > > [[alternative HTML version deleted]] > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] the making of _R_ eBooks
> Q3: any other recommendations? You might be interested in the very easy to use R markdown, see: http://rmarkdown.rstudio.com/ [[alternative HTML version deleted]] __ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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] changing column labels for data frames inside a list
On 30 March 2015 at 16:47, Sarah Goslee wrote: > colnames(e) <- paste0('pop',1:12) > > isn't a function and doesn't return anything. > But function(e){colnames(e) <- paste0('pop', 1:2)} is a function and it returns something (the last evaluated expression! - here the paste0 return): > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', 1:2)}) > mylist2 [[1]] [1] "pop1" "pop2" [[2]] [1] "pop1" "pop2" [[3]] [1] "pop1" "pop2" from ?return: If the end of a function is reached without calling return, the value of the last evaluated expression is returned. > > > mylist <- list( > + data.frame(a = runif(10), b = runif(10)), > + data.frame(c = runif(10), d = runif(10)), > + data.frame(e = runif(10), f = runif(10))) > > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', 1:2); > e}) > > colnames(mylist2[[1]]) > [1] "pop1" "pop2" > > Sarah > > On Mon, Mar 30, 2015 at 9:54 AM, Vikram Chhatre > wrote: > >> summary(mygenfreqt) > > Length Class Mode > > dat1.str 59220 -none- numeric > > dat2.str 59220 -none- numeric > > dat3.str 59220 -none- numeric > > > >> head(mylist[[1]]) > >1 2 3 4 5 6 7 8 91011 > > 12 > > L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 0.350 > > 0.275 > > L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 0.650 > > 0.725 > > > > I want to change 1:12 to pop1:pop12 > > > > mylist<- lapply(mylist, function(e) colnames(e) <- paste0('pop',1:12)) > > > > What this is doing is replacing the data frames with just names > > pop1:pop12. I just want to replace the column labels. > > > > Thanks for any suggestions. > > > > -- > Sarah Goslee > http://www.functionaldiversity.org > > __ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] changing column labels for data frames inside a list
On 30 March 2015 at 17:19, Vikram Chhatre wrote: > First of all, thank you for all the quick replies. Here is a solution that > worked for me. > > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop',1:12); > return(e)}) > > > head(mylist2[[1]]) > pop1 pop2 pop3 pop4 pop5 pop6 pop7 pop8 pop9 pop10 pop11 > pop12 > L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 0.350 > 0.275 > L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 0.650 > 0.725 > > While we are at this, I wanted to create a 13th column in each data frame > for average of each row. > For new problems you should use a new topic. > > # Calculate average > myavg <- lapply(mylist2, function(e) rowSums(mylist2)/12) > > # Attach to the main data frame > mylist3 <- cbind(mylist2, myavg) > > This does not work the way I imagined it would. The myavg vector is > attached directly to mylist2, not to individual dataframes within. > > But it works as expected (read ?cbind). You try to cbind two lists (myavg and mylist2). You want to cbind each list object (the data.frames) with each rowSums output. So, use cbind within your first lapply. p.s. Is it a standard convention to always copy the reply to the last > person who responded? > I guess it depends on which answer you refer to. > > On Mon, Mar 30, 2015 at 10:56 AM, Sven E. Templer > wrote: > > > On 30 March 2015 at 16:47, Sarah Goslee wrote: > > > > > colnames(e) <- paste0('pop',1:12) > > > > > > isn't a function and doesn't return anything. > > > > > > > But > > function(e){colnames(e) <- paste0('pop', 1:2)} > > is a function and it returns something (the last evaluated expression! - > > here the paste0 return): > > > > > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > 1:2)}) > > > mylist2 > > [[1]] > > [1] "pop1" "pop2" > > > > [[2]] > > [1] "pop1" "pop2" > > > > [[3]] > > [1] "pop1" "pop2" > > > > from ?return: > > > > If the end of a function is reached without calling return, the value of > > the last evaluated expression is returned. > > > > > > > > > mylist <- list( > > > + data.frame(a = runif(10), b = runif(10)), > > > + data.frame(c = runif(10), d = runif(10)), > > > + data.frame(e = runif(10), f = runif(10))) > > > > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > > 1:2); > > > e}) > > > > colnames(mylist2[[1]]) > > > [1] "pop1" "pop2" > > > > > > Sarah > > > > > > On Mon, Mar 30, 2015 at 9:54 AM, Vikram Chhatre > > > wrote: > > > >> summary(mygenfreqt) > > > > Length Class Mode > > > > dat1.str 59220 -none- numeric > > > > dat2.str 59220 -none- numeric > > > > dat3.str 59220 -none- numeric > > > > > > > >> head(mylist[[1]]) > > > >1 2 3 4 5 6 7 8 910 > > 11 > > > > 12 > > > > L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 > > 0.350 > > > > 0.275 > > > > L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 > > 0.650 > > > > 0.725 > > > > > > > > I want to change 1:12 to pop1:pop12 > > > > > > > > mylist<- lapply(mylist, function(e) colnames(e) <- > paste0('pop',1:12)) > > > > > > > > What this is doing is replacing the data frames with just names > > > > pop1:pop12. I just want to replace the column labels. > > > > > > > > Thanks for any suggestions. > > > > > > > > > > -- > > > Sarah Goslee > > > http://www.functionaldiversity.org > > > > > > __ > > > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > > > 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 -- To UNSUBSCRIBE and more, see > > 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 -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] changing column labels for data frames inside a list
On 30 March 2015 at 17:31, Bert Gunter wrote: > Sarah's statement is correct. > > So is yours. They are not contradictory, and I believe Sarah's point > was that the OP needed to learn the appropriate syntax. > > That's why I pointed to ?return. Sarah's statement was not so clear (and might have been misleading) for me regarding the R expertise of the OP. > -- Bert > > Bert Gunter > Genentech Nonclinical Biostatistics > (650) 467-7374 > > "Data is not information. Information is not knowledge. And knowledge > is certainly not wisdom." > Clifford Stoll > > > > > On Mon, Mar 30, 2015 at 7:56 AM, Sven E. Templer > wrote: > > On 30 March 2015 at 16:47, Sarah Goslee wrote: > > > >> colnames(e) <- paste0('pop',1:12) > >> > >> isn't a function and doesn't return anything. > >> > > > > But > > function(e){colnames(e) <- paste0('pop', 1:2)} > > is a function and it returns something (the last evaluated expression! - > > here the paste0 return): > > > >> mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > 1:2)}) > >> mylist2 > > [[1]] > > [1] "pop1" "pop2" > > > > [[2]] > > [1] "pop1" "pop2" > > > > [[3]] > > [1] "pop1" "pop2" > > > > from ?return: > > > > If the end of a function is reached without calling return, the value of > > the last evaluated expression is returned. > > > >> > >> > mylist <- list( > >> + data.frame(a = runif(10), b = runif(10)), > >> + data.frame(c = runif(10), d = runif(10)), > >> + data.frame(e = runif(10), f = runif(10))) > >> > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > 1:2); > >> e}) > >> > colnames(mylist2[[1]]) > >> [1] "pop1" "pop2" > >> > >> Sarah > >> > >> On Mon, Mar 30, 2015 at 9:54 AM, Vikram Chhatre > >> wrote: > >> >> summary(mygenfreqt) > >> > Length Class Mode > >> > dat1.str 59220 -none- numeric > >> > dat2.str 59220 -none- numeric > >> > dat3.str 59220 -none- numeric > >> > > >> >> head(mylist[[1]]) > >> >1 2 3 4 5 6 7 8 910 > 11 > >> > 12 > >> > L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 > 0.350 > >> > 0.275 > >> > L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 > 0.650 > >> > 0.725 > >> > > >> > I want to change 1:12 to pop1:pop12 > >> > > >> > mylist<- lapply(mylist, function(e) colnames(e) <- paste0('pop',1:12)) > >> > > >> > What this is doing is replacing the data frames with just names > >> > pop1:pop12. I just want to replace the column labels. > >> > > >> > Thanks for any suggestions. > >> > > >> > >> -- > >> Sarah Goslee > >> http://www.functionaldiversity.org > >> > >> __ > >> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > >> 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 -- To UNSUBSCRIBE and more, see > > 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 -- To UNSUBSCRIBE and more, see 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] changing column labels for data frames inside a list
On 30 March 2015 at 17:50, Sarah Goslee wrote: > On Mon, Mar 30, 2015 at 11:43 AM, Sven E. Templer > wrote: > > > > > > On 30 March 2015 at 17:31, Bert Gunter wrote: > >> > >> Sarah's statement is correct. > >> > >> So is yours. They are not contradictory, and I believe Sarah's point > >> was that the OP needed to learn the appropriate syntax. > >> > > > > That's why I pointed to ?return. > > Sarah's statement was not so clear (and might have been misleading) for > me > > regarding the R expertise of the OP. > > You're right: I totally wasn't clear. I got involved making a working > reproducible example and didn't explain what I was doing. And you are > totally correct, the last expression will be returned. Mea culpa. > > No one to blame but the missing reproducible example, I agree! Sven > Sarah > > > >> > >> -- Bert > >> > >> Bert Gunter > >> Genentech Nonclinical Biostatistics > >> (650) 467-7374 > >> > >> "Data is not information. Information is not knowledge. And knowledge > >> is certainly not wisdom." > >> Clifford Stoll > >> > >> > >> > >> > >> On Mon, Mar 30, 2015 at 7:56 AM, Sven E. Templer < > sven.temp...@gmail.com> > >> wrote: > >> > On 30 March 2015 at 16:47, Sarah Goslee > wrote: > >> > > >> >> colnames(e) <- paste0('pop',1:12) > >> >> > >> >> isn't a function and doesn't return anything. > >> >> > >> > > >> > But > >> > function(e){colnames(e) <- paste0('pop', 1:2)} > >> > is a function and it returns something (the last evaluated > expression! - > >> > here the paste0 return): > >> > > >> >> mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > >> >> 1:2)}) > >> >> mylist2 > >> > [[1]] > >> > [1] "pop1" "pop2" > >> > > >> > [[2]] > >> > [1] "pop1" "pop2" > >> > > >> > [[3]] > >> > [1] "pop1" "pop2" > >> > > >> > from ?return: > >> > > >> > If the end of a function is reached without calling return, the value > of > >> > the last evaluated expression is returned. > >> > > >> >> > >> >> > mylist <- list( > >> >> + data.frame(a = runif(10), b = runif(10)), > >> >> + data.frame(c = runif(10), d = runif(10)), > >> >> + data.frame(e = runif(10), f = runif(10))) > >> >> > mylist2 <- lapply(mylist, function(e){colnames(e) <- paste0('pop', > >> >> > 1:2); > >> >> e}) > >> >> > colnames(mylist2[[1]]) > >> >> [1] "pop1" "pop2" > >> >> > >> >> Sarah > >> >> > >> >> On Mon, Mar 30, 2015 at 9:54 AM, Vikram Chhatre > >> >> wrote: > >> >> >> summary(mygenfreqt) > >> >> > Length Class Mode > >> >> > dat1.str 59220 -none- numeric > >> >> > dat2.str 59220 -none- numeric > >> >> > dat3.str 59220 -none- numeric > >> >> > > >> >> >> head(mylist[[1]]) > >> >> >1 2 3 4 5 6 7 8 910 > >> >> > 11 > >> >> > 12 > >> >> > L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 > >> >> > 0.350 > >> >> > 0.275 > >> >> > L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 > >> >> > 0.650 > >> >> > 0.725 > >> >> > > >> >> > I want to change 1:12 to pop1:pop12 > >> >> > > >> >> > mylist<- lapply(mylist, function(e) colnames(e) <- > >> >> > paste0('pop',1:12)) > >> >> > > >> >> > What this is doing is replacing the data frames with just names > >> >> > pop1:pop12. I just want to replace the column labels. > >> >> > > >> >> > Thanks for any suggestions. > >> >> > > >> >> > >> >> -- > >> >> Sarah Goslee > >> >> http://www.functionaldiversity.org > [[alternative HTML version deleted]] __ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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] idiom for constructing data frame
If you don't mind an extra column, you could use something similar to: data.frame(r=seq(8),foo=NA,bar=NA) If you do, here is another approach (see function body): empty.frame <- function (r = 1, n = 1, fill = NA_real_) { data.frame(setNames(lapply(rep(fill, length(n)), rep, times=r), n)) } empty.frame() empty.frame(, seq(3)) empty.frame(8, c("foo", "bar")) I could not put it in one line either, without retyping at least one argument (n in this case). So I suggest a function is the way to go for a simplified syntax ... Thanks to all for the ideas! Sven On 31 March 2015 at 20:55, William Dunlap wrote: > You can use structure() to attach the names to a list that is input to > data.frame. > E.g., > > dfNames <- c("First", "Second Name") > data.frame(lapply(structure(dfNames, names=dfNames), > function(name)rep(NA_real_, 5))) > > > Bill Dunlap > TIBCO Software > wdunlap tibco.com > > On Tue, Mar 31, 2015 at 11:37 AM, Sarah Goslee > wrote: > > > Hi, > > > > Duncan Murdoch suggested: > > > > > The matrix() function has a dimnames argument, so you could do this: > > > > > > names <- c("strat", "id", "pid") > > > data.frame(matrix(NA, nrow=10, ncol=3, dimnames=list(NULL, names))) > > > > That's a definite improvement, thanks. But no way to skip matrix()? It > > just seems unRlike, although since it's only full of NA values there > > are no coercion issues with column types or anything, so it doesn't > > hurt. It's just inelegant. :) > > > > Sarah > > -- > > Sarah Goslee > > http://www.functionaldiversity.org > > > > __ > > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > > 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 -- To UNSUBSCRIBE and more, see > 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 -- To UNSUBSCRIBE and more, see 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] How to use multi paragraph comment like /* and */ in cpp?
One way I know to do this is (in bash) to use a dummy variable and make the comment a multiline character string: dummy <- c(" This is my multiline comment or code block. ") or if printing does not disturb you, just use: " ... " Use ' if you have " in the block. Other workarounds are here, which you find when using a search engine: http://stackoverflow.com/questions/1231195/multiline-comment-workarounds Hope this helps. @Duncan: sorry sending the mail to you twice. Sven On 9 September 2014 13:43, Duncan Murdoch wrote: > On 08/09/2014, 11:14 PM, Jeff Newmiller wrote: >> There are no multi line comment markers in R. However, since you are always >> referring to RStudio you might want to look into roxygen, since their editor >> supports that tool. > > RStudio has a command to comment a block: it's in the Code menu. (On > my Mac the shortcut is C :-). > > Duncan Murdoch > > >> >> I would also suggest making more functions that are smaller. >> --- >> Jeff NewmillerThe . . Go Live... >> DCN:Basics: ##.#. ##.#. Live Go... >> Live: OO#.. Dead: OO#.. Playing >> Research Engineer (Solar/BatteriesO.O#. #.O#. with >> /Software/Embedded Controllers) .OO#. .OO#. rocks...1k >> --- >> Sent from my phone. Please excuse my brevity. >> >> On September 8, 2014 7:49:32 PM PDT, PO SU wrote: >>> >>> Dear expeRts, >>>I find it's terrible when i want to comment multi paragraph (e.g. >>> a 30 lines function) , i have to comment each line with #, is there >>> any good way to do that ? >>>I investgate it, but found no easy way, may you help me ? >>> >>> >>> >>> >>> >>> -- >>> >>> PO SU >>> mail: desolato...@163.com >>> Majored in Statistics from SJTU >>> __ >>> 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-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] adding rows
see inline for another vectorized example. On 25 September 2014 23:05, David L Carlson wrote: > Another approach > > fun <- function(i, dat=x) { > grp <- rep(1:(nrow(dat)/i), each=i) > aggregate(dat[1:length(grp),]~grp, FUN=sum) > } > > lapply(2:6, fun, dat=TT) > > > - > David L Carlson > Department of Anthropology > Texas A&M University > College Station, TX 77840-4352 > > -Original Message- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of Rui Barradas > Sent: Thursday, September 25, 2014 3:34 PM > To: eliza botto; r-help@r-project.org > Subject: Re: [R] adding rows > > Hello, > > Try the following. > > fun <- function(x, r){ > if(r > 0){ > m <- length(x) %/% r > y <- numeric(m) > for(i in seq_len(m)){ > y[i] <- sum(x[((i - 1)*r + 1):(i*r)]) > } > y > }else{ > NULL > } > } fun <- function(x,r) { i <- length(x)%/%r tapply(x[1:(i*r)], gl(i,r), sum) } > > apply(TT, 2, fun, r = 2) > apply(TT, 2, fun, r = 3) > etc > > > Hope this helps, > > Rui Barradas > > > Em 25-09-2014 20:50, eliza botto escreveu: >> Dear useRs, >> Here is my data with two columns and 20 rows. >>> dput(TT) >> structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, >> 19, 20, 24, 48, 72, 96, 120, 144, 168, 192, 216, 240, 264, 288, 312, 336, >> 360, 384, 408, 432, 456, 480), .Dim = c(20L, 2L), .Dimnames = list(NULL, >> c("", "SS"))) >> I first of all want to sum up continuously two rows (1 & 2, 3 & 4, 5 & 6 >> and so on) of each column. >> Then I want to sum up 3 rows as (1-2-3,4-5-6,. 16-17-18) and since 19th >> and 20th rows do not up 3 rows, so they should be ignored. >> Similarly with 4 sets of rows and 5 sets of rows and even 6. >> I hope I was clear. >> Thankyou so very much in advance, >> Eliza >> [[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-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] how to get the rows that satisfy a specific condition
in ?which read about arr.ind following jims assumption (column instead of row indices is what you want) this also works: m <- matrix(1:20,4) unique(which(m>11, arr.ind = T)[,"col"]) On 27 September 2014 12:23, Jim Lemon wrote: > On Fri, 26 Sep 2014 10:15:14 PM Fix Ace wrote: >> Hello, there, >> I wonder if there is an easier way that I would only get the rows that >> satisfies some condition. For example:I have the following matrix, and I >> would like to output only the 3rd row and 4th row, since only these two >> rows contain the numbers greater than 11 >> > a >> >> [,1] [,2] [,3] [,4] [,5] >> [1,]159 13 17 >> [2,]26 10 14 18 >> [3,]37 11 15 19 >> [4,]48 12 16 20 >> >> > a>11 >> >> [,1] [,2] [,3] [,4] [,5] >> [1,] FALSE FALSE FALSE TRUE TRUE >> [2,] FALSE FALSE FALSE TRUE TRUE >> [3,] FALSE FALSE FALSE TRUE TRUE >> [4,] FALSE FALSE TRUE TRUE TRUE >> I have tried to use a[a>11, ] and it did not work. >> Thanks a lot for the help:) > > Hi Fix Ace, > I have to admit that I am unfamiliar with the system of arithmetic that > you are employing in the above example. In no system with which I am > conversant are 13, 17, 14 and 18 less than or equal to 11. I can only > offer the desperate conjecture that you want the third to fifth columns of > the matrix rather than the third and fourth rows. If this wild surmise > happens to be the case, I suggest that you try this: > > testmat[,apply(testmat,2,function(x) return(max(x) > 11))] > > Jim > > __ > 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] Obtain 00Index.html
Hello, how can I open (by an R command) the index page in html mode, as obtained by: options(browser="firefox") # or any other options(help_type="html") ?help # and then following the html reference on the page bottom named "Index" In text mode I know library(help='utils') to open the utils package index (as in the example above). Setting options(text_mode="html") and options(browser="firefox") does not affect this behaviour. Also in ?help.start and ?help (or ?"?") I found no clues. Thank you for any hints, Sven. __ 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] Function on an array
Dear Barry, some thoughts: 1) e in your function status_fnc is a vector when applied on a matrix like object, but you index it as a matrix (e[,i] should be e[i]). 2) You can simplify the if statement by using the function any (replacing all the OR statements) on the vector, so use any(e=='Y') here. 3) sapply applies over a list, which your object isn't. You provide a matrix (cbind), so you should use apply in that case. So one solution might be: ex1 <- c('Y', 'N', 'Y') ex2 <- c('Y', 'N', 'Y') ex3 <- c('N', 'N', 'Y') ex4 <- c('N', 'N', 'Y') status_fnc <- function(e){ if (any(e=='Y')) return('Okay') else return('Not okay') } status <- apply(cbind(ex1, ex2, ex3, ex4), 1, status_fnc) status On 8 October 2014 12:54, Barry King wrote: > ex1 <- c('Y', 'N', 'Y') > ex2 <- c('Y', 'N', 'Y') > ex3 <- c('N', 'N', 'Y') > ex4 <- c('N', 'N', 'Y') > > status <- array(NA, dim=3) > > # I am trying to return 'Okay' if any of the values > # in a column above is 'Y' but I am not constructing > # the function corrrectly. Any assistance is > # greatly appreciated > > status_fnc <- function(e){ > if (e[ ,1] == 'Y' | e[ ,2] == 'Y' | e[ ,3] == 'Y' | e[ ,4] == 'Y'){ > return('Okay') > } else return('Not okay') > } > status <- sapply(cbind(ex1, ex2, ex3, ex4), status_fnc) > > [[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.
Re: [R] (no subject)
follow instructions on https://stat.ethz.ch/mailman/listinfo/r-help at "To unsubscribe from R-help, get a password reminder, or change your subscription options enter your subscription email address: " ... On 10 October 2014 16:16, Tasnuva Tabassum wrote: > I want to get rid of this thread. what to do? > > [[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.
Re: [R] evaluate NA to FALSE instead of NA?
use: which(p<=.05) this will not yield logical, but integer indices without NA On 14 October 2014 11:51, Rainer M Krug wrote: > Hi > > I want to evaluate NA and NaN to FALSE (for indexing) so I would like to > have the result as indicated here: > > , > | > p <- c(1:10/100, NA, NaN) > | > p > | [1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 NA NaN > | > p[p<=0.05] > | [1] 0.01 0.02 0.03 0.04 0.05 NA NA > | > p[sapply(p<=0.05, isTRUE)] > | [1] 0.01 0.02 0.03 0.04 0.05 <<<=== I want this > ` > > Is there a way that I can do this more easily then in my example above? > It works, but it strikes me that there is not a better way of doing > this - am I missing a command or option? > > Thanks, > > Rainer > > -- > Rainer M. Krug > email: Rainerkrugsde > PGP: 0x0F52F982 > > __ > 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] package installation failure virtualisation environment
Prevent graphic menues with: options(menu.graphics = FALSE) or and define repositories: options(repos = c(CRAN = "http://cran.r-project.org";)) On 14 October 2014 17:00, wrote: > Subscribers, > > A version of R is installed in a virtual machine, which has complete > internet access via the host. > > The following error occurs when a package is selected: > > install.packages([packagename], dependencies=TRUE) > --- Please select a CRAN mirror for use in this session --- > Killed > > The error also occurs with: > > install.packages() > > The process is killed as shown previously (but not the R session), after > selection of a package in the Tcl/tk dialogue window. > > The error occurs both as root and normal user. > > Any suggestions please to solve? > > R.version >_ > platform i686-pc-linux-gnu > arch i686 > os linux-gnu > system i686, linux-gnu > status > major 3 > minor 1.1 > year 2014 > month 07 > day10 > svn rev66115 > language R > version.string R version 3.1.1 (2014-07-10) > nickname Sock it to Me > > __ > 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] package installation failure virtualisation environment
did you check the connection in R via for example: head(readLines("http://cran.r-project.org/web/licenses/GPL-3";)) which should yield: [1] "GNU GENERAL PUBLIC LICENSE" [2] " Version 3, 29 June 2007" [3] "" [4] " Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>" [5] " Everyone is permitted to copy and distribute verbatim copies" [6] " of this license document, but changing it is not allowed." On 15 October 2014 10:51, wrote: > On 2014-10-14 15:40, Sven E. Templer wrote: >> >> Prevent graphic menues with: >> options(menu.graphics = FALSE) > > > Same response after a pause: 'Killed' > >> or and define repositories: >> options(repos = c(CRAN = "http://cran.r-project.org";)) >> > > Same response after a pause: 'Killed' > > __ 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] add text to the first line of an output file
Hi. You can't. But using a second file where you first write your header and then append the original file is a solution. ?cat and ?write.table with a focus on the 'append' argument should help. you can then use ?unlink to delete the original file and ?file.rename to rename the second, if desired. Best, Sven. On 22 October 2014 02:32, YIHSU CHEN wrote: > Hi guys; > > I want to write some text at the first line of an output file. The output > file will be used for other software. In particular, the following text > "ampl.tab 2 1" needs to be added to the first line of an df output file. > As a hypothetic example, the output in text file should be like: > > ampl.tab 2 1 > A B > 2 3 > 4 6 > 2 0 > > Thanks for help. > > Yihsu > > [[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.
Re: [R] add text to the first line of an output file
He wants to prepend, not append. On 22 October 2014 11:04, Henrik Bengtsson wrote: > You can! Open a file connection and write to that. Whatever write commands > you use will append to the output. Don't forget to close the connection at > the end. See ?file > > Henrik > > On Oct 22, 2014 12:33 AM, "Sven E. Templer" wrote: >> >> Hi. >> >> You can't. >> >> But using a second file where you first write your header and then >> append the original file is a solution. ?cat and ?write.table with a >> focus on the 'append' argument should help. you can then use ?unlink >> to delete the original file and ?file.rename to rename the second, if >> desired. >> >> Best, Sven. >> >> On 22 October 2014 02:32, YIHSU CHEN wrote: >> > Hi guys; >> > >> > I want to write some text at the first line of an output file. The >> > output >> > file will be used for other software. In particular, the following text >> > "ampl.tab 2 1" needs to be added to the first line of an df output >> > file. >> > As a hypothetic example, the output in text file should be like: >> > >> > ampl.tab 2 1 >> > A B >> > 2 3 >> > 4 6 >> > 2 0 >> > >> > Thanks for help. >> > >> > Yihsu >> > >> > [[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-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] creating individual records from a frequency distribution
With melt and rep you are close. If you combine them it works: library(reshape) # your data: df1 <- data.frame(area=c(1,2),group1=c(2,3),group2=c(1,5),group3=c(4,0)) df2<-data.frame(person_id=seq(1:15),area=c(rep(1,7),rep(2,8)),group_num=c(1,1,2,3,3,3,3,1,1,1,2,2,2,2,2)) # first melt d <- melt(df1,"area",2:4) # then repeat each row by 'counts' d <- d[rep(seq(nrow(d)), times=d$value),] # then order (if order of id's is not arbitrary), and add ids d <- d[order(d$area,d$variable),] d$value <- seq(nrow(d)) # compare cbind(df2,"---",d) Best, Sven. On 22 October 2014 17:48, Gavin Rudge wrote: > I've got data frame containing a simple frequency distribution of numbers of > people in three age groups by area. > > df1<-data.frame(area=c(1,2),group1=c(2,3),group2=c(1,5),group3=c(4,0)) > df1 > > I want to get a data frame with one record per person (in my case 15 of them) > which would look like this, with variables indicating the area and age group > to which each belongs > > df2<-data.frame(person_id=seq(1:15),area=c(rep(1,7),rep(2,8)),group_num=c(1,1,2,3,3,3,3,1,1,1,2,2,2,2,2)) > df2 > > This is not the same as melting wide to long data as in reshape2, as I'm > melting from aggregated data. I can get vectors of columns values using the > rep command, but sewing them together and allowing for zeros looks a bit > cumbersome. I'm assuming there is a simple command that does this sort of > thing. > > Any help gratefully received, > > GavinR > > [[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.
Re: [R] sort a data.frame in a different way
seems like a transpose, so use ?t t(your.data.frame) On 22 October 2014 11:34, Matthias Weber wrote: > Hello together, > > i have a little problem. Maybe anyone can help me. > > I have a data. frame which look like this one: > 1000 1001 10021003 > 15 6 1211 > 24 3 81 > > What i need is a data.frame, which looks like this one. The Column names > should be in the first column, and the values right of the column name. The > solution look like this one: > A B > 1000 5 4 > 1001 6 3 > 1002 12 8 > 1003 11 1 > > maybe anyone can help me. > > Thank you. > > Best regards. Mat > > > > This e-mail may contain trade secrets, privileged, undisclosed or otherwise > confidential information. If you have received this e-mail in error, you are > hereby notified that any review, copying or distribution of it is strictly > prohibited. Please inform us immediately and destroy the original > transmittal. Thank you for your cooperation. > > Diese E-Mail kann Betriebs- oder Geschaeftsgeheimnisse oder sonstige > vertrauliche Informationen enthalten. Sollten Sie diese E-Mail irrtuemlich > erhalten haben, ist Ihnen eine Kenntnisnahme des Inhalts, eine > Vervielfaeltigung oder Weitergabe der E-Mail ausdruecklich untersagt. Bitte > benachrichtigen Sie uns und vernichten Sie die empfangene E-Mail. Vielen Dank. > > [[alternative HTML version deleted]] please read mailing list guidelines, and don't send HTML messages > > __ > 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] Formula with dynamic number of variables
# fixed formula part: f <- dat ~ a0 * exp(-S*(x - 250)) + K # convert to character f <- as.character(f) # component: C <- "(p0*exp(-0.5*((x-p1)/p2)^2))" # number of components (defined randomly): n <- sample(1:3, 1) C <- rep(C, n) # collapse: C <- paste(C, collapse = "+") # combine f <- paste(f[2], f[1], f[3], "+", C) as.formula(f) # hope this helps. # best, s On 21 November 2014 at 14:23, philippe massicotte wrote: > Hi everyone. > > I have a non-linear model specified as this (6 variables, a0, S, K, p0, p1, > p2): > > fit <- nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( C ) ) > > where C = (p0*exp(-0.5*((x-p1)/p2)^2)) > > The problem is that I do not know in advance how many component (C) I will > have in the model. That means It could be: > > nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( > (p0*exp(-0.5*((x-p1)/p2)^2)) ) ) > > or > > nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( > (p0*exp(-0.5*((x-p1)/p2)^2)) ) + ( (p0b*exp(-0.5*((x-p1b)/p2b)^2)) )) > > or > > > nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( > (p0*exp(-0.5*((x-p1)/p2)^2)) ) + ( (p0b*exp(-0.5*((x-p1b)/p2b)^2)) + ( > (p0c*exp(-0.5*((x-p1c)/p2c)^2 > > So I was wondering if it was possible to dynamically build the formula that I > will use in my model? The first part of my model will always be "a0 * > exp(-S*(x - 250)) + K", I just want to add a certain number of "components" > dynamically. > > I guess it will be related with "reformulate()" but I can't not find how to > make it works. > > Thank you for your help, > Philippe > > > [[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.