Stat-R
Stat-R

Reputation: 5280

Concatenating strings with

I have a data frame with several variables. What I want is create a string using (concatenation) the variable names but with something else in between them...

Here is a simplified example (number of variables reduced to only 3 whereas I have actually many)

Making up some data frame

 df1 <- data.frame(1,2,3) # A one row data frame
  names(df1) <- c('Location1','Location2','Location3') 

Actual code...

  len1 <- ncol(df1)
  string1 <- 'The locations that we are considering are'  
    for(i in 1:(len1-1))   string1 <- c(string1,paste(names(df1[i]),sep=','))

  string1 <- c(string1,'and',paste(names(df1[len1]),'.'))
  string1

This gives...

[1] "The locations that we are considering are"
[2] "Location1"                          
[3] "Location2"                          
[4] "Location3 ."

But I want

The locations that we are considering are Location1, Location2 and Location3.

I am sure there is a much simpler method which some of you would know... Thank you for you time...

Upvotes: 9

Views: 46864

Answers (4)

johannes
johannes

Reputation: 14453

An other options would be:

library(stringr)
str_c("The location that we are consiering are ", str_c(str_c(names(df1)[1:length(names(df1))-1], collapse=", "), names(df1)[length(names(df1))], sep=" and "))

Upvotes: 0

Brian Diggs
Brian Diggs

Reputation: 58845

The fact that these are names of a data.frame does not really matter, so I've pulled that part out and assigned them to a variable strs.

strs <- names(df1)
len1 <- length(strs)
string1 <- paste("The locations that we are considering are ", 
                 paste(strs[-len1], collapse=", ", sep=""),
                 " and ",
                 strs[len1], 
                 ".\n", 
                 sep="")

This gives

> cat(string1)
The locations that we are considering are Location1, Location2 and Location3.

Note that this will not give sensible English if there is only 1 element in strs.

The idea is to collapse all but the last string with comma-space between them, and then paste that together with the boilerplate text and the last string.

Upvotes: 5

Greg Snow
Greg Snow

Reputation: 49660

If your main goal is to print the results to the screen (or other output) then use the cat function (whose name derives from concatenate):

> cat(names(iris), sep=' and '); cat('\n')
Sepal.Length and Sepal.Width and Petal.Length and Petal.Width and Species

If you need a variable with the string, then you can use paste with the collapse argument. The sprintf function can also be useful for inserting strings into other strings (or numbers into strings).

Upvotes: 2

cbeleites
cbeleites

Reputation: 14093

Are you looking for the collapse argument of paste?

> paste (letters [1:3], collapse = " and ")
[1] "a and b and c"

Upvotes: 22

Related Questions