Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste together two character vectors of different lengths

Tags:

r

paste

I have two different character vectors in R, that I want to combine to use for column names:

groups <- c("Group A", "Group B")
label <- c("Time","Min","Mean","Max")

When I try using paste I get the result:

> paste(groups,label)
[1] "Group A Time" "Group B Min"  "Group A Mean" "Group B Max"

Is there a simple function or setting that can paste these together to get the following output?

[1] "Group A Time" "Group A Min"  "Group A Mean" "Group A Max"  "Group B Time"
[6] "Group B Min"  "Group B Mean" "Group B Max" 
like image 792
bigjim Avatar asked Sep 02 '11 17:09

bigjim


People also ask

How do you combine character vectors?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.

How do I paste a character vector in R?

You can use the paste() and paste0() functions in R to concatenate elements of a vector into a single string. The paste() function concatenates strings using a space as the default separator. The paste0() function concatenates strings using no space as the default separator.

What is a character vector?

Character/string – each element in the vector is a string of one or more characters. Built in character vectors are letters and LETTERS which provide the 26 lower (and upper) case letters, respecitively. > y = c("a", "bc", "def")


2 Answers

Probably outer helps your work. Try this:

> c(t(outer(groups, label, paste)))
[1] "Group A Time" "Group A Min"  "Group A Mean" "Group A Max"  "Group B Time" "Group B Min" 
[7] "Group B Mean" "Group B Max" 
like image 117
kohske Avatar answered Oct 07 '22 20:10

kohske


outer

outer(groups, labels, FUN=paste)

like image 29
IRTFM Avatar answered Oct 07 '22 19:10

IRTFM