[R] help with paste

Joshua Wiley jwiley.psych at gmail.com
Thu Oct 27 07:10:04 CEST 2011


Hi Sharad,

See ?paste, particularly the 'collapse' argument:

> mols=c("LEPTIN","SAA","PTH","sEGFR")
> paste(mols[1:3], collapse = " + ")
[1] "LEPTIN + SAA + PTH"

If this is going to ultimately end up in regression (my spidey sense
is tingling), the follow up question you will have is something like:

"I have a bunch of string variables that I am trying to use in a
formula in lm() but it isn't work".

then there will be a series of possible hacks to shoehorn character
data into the formula.  Here is a pre-emptive suggestion (of many
possibilities) using the mtcars dataset in R.  Suppose 'mpg' is always
the outcome, and then you want all sets of 2 predictors:

## make a data frame where each column represents all the variables
for one model
varset <- data.frame(rbind("mpg", combn(colnames(mtcars)[-1], 2)),
stringsAsFactors = FALSE)

## looks like this:
> varset[, 1:3]
    X1  X2   X3
1  mpg mpg  mpg
2  cyl cyl  cyl
3 disp  hp drat

## fit a separate model of mpg regressed on every other variable in the dataset
## but subset mtcars by each column of varset
## store results in one big list

allmodels <- lapply(varset, function(i) {
  lm(mpg ~ ., data = mtcars[, i])
})

## extract all coefficients into a matrix
sapply(allmodels, coef)

note that with this general method I am proposing, all models need not
have the same number of predictors.  I just did it for convenience so
I could use the combn() function to generate a bunch of combinations.

Cheers,

Josh

On Wed, Oct 26, 2011 at 6:03 PM, 1Rnwb <sbpurohit at gmail.com> wrote:
> Hello gurus,
>
> I have some variables, and i am creating combinations for analysis in the
> end i need these variables to be displayed like "LEPTIN+SAA+PTH". currently
> i am using loop to perform this. I would appreciate any pointers to do it
> without the loop.
>
>> mols=c("LEPTIN","SAA","PTH","sEGFR")
>> samples=mols[1:3]
>> samples
> [1] "LEPTIN" "SAA"    "PTH"
>> names1=samples[1]
>>  for (j in 2:length(samples)){ names1 = paste (names1, samples[j],
>> sep="+")}
>> names1
> [1] "LEPTIN+SAA+PTH"
>>
> thanks
> sharad
>
> --
> View this message in context: http://r.789695.n4.nabble.com/help-with-paste-tp3942818p3942818.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list