I have a dataframe with two colmns:
C1 <- c("abcd > de > efg", "hij > kl > iiii", "aa", "a > bbb")
C2 <- c("1980","1982","1989","1989")
df <- data.frame(C1, C2, stringsAsFactors = FALSE)
My goal is concatenate the arguments of the 2 of them like this:
result <- c("1980abcd > 1980de > 1980efg", "1982hij > 1982kl > 1982iiii", "1989aa", "1989a > 1989bbb")
How can i do that? Thanks.
One way via base R is to use split the C1
vector and use mapply
to paste with C2
, i.e.
v1 <- mapply(function(x, y) paste(paste0(x, y), collapse = ' > '), C2, strsplit(C1, ' > '))
unname(v1)
#[1] "1980abcd > 1980de > 1980efg" "1982hij > 1982kl > 1982iiii" "1989aa" "1989a > 1989bbb"
NOTE: The result of mapply
(i.e. v1
) is a named vector. Hence I used unname
to get to your desired structure. However, note that a named vector is still a vector and will behave as such.