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))
1
  • What happened? Was it not as expected? Commented Jul 6, 2017 at 14:17

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I also need to concatenate "a" with "low" and "average"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.