0

Here is my sample:

stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)

data <- data.frame(stringa,stringb,index)

I would like to concatenate stringa and stringb, and attach the corresponding index in another column. For example, the first row of the result should be "a high" with index "1".

Now I have used this function to concatenate the two strings:

c(outer(a, b, paste))
Ran Tao
  • 311
  • 1
  • 4
  • 13

1 Answers1

1

For "a high", "b low", "c average" you can do:

stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)
data.frame(concatenated = paste(stringa, stringb),index)
  concatenated
1    a high
2    b low
3    c average

For the full permutations of stringa and stringb:

stringa = c("a","b","c")
stringb = c("high","low","average")
data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
    concatenated
1       a high
2       b high
3       c high
...
9    c average

If you want to explicitly add the row index:

df = data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
df$index = rownames(df)
df 
  concatenated index
1       a high     1
2       b high     2
3       c high     3
...
9    c average     9
Y.L
  • 694
  • 12
  • 26