digit
digit

Reputation: 1523

Paste value after certain delimiter

I have data in the following format:

In Column A:

String1__String2__String3

In Column B:

Value

I would like to paste the Value into the String after the first delimiter like this:

String1__Value__String2__String3

The crucial part of the code I am using now (where I paste the value) is the following line:

df2 <-cbind(df[1],apply(df[,2:ncol(df)],2,function(i)ifelse(is.na(i), NA, paste(df[,1],i,sep="_")))) 

With this code it append the value after the string, like this:

String1__String2__String3__Value

Is there an easy way to rearrange this so the Values will be pasted at the correct place. Or do I have to redo the complete code ?

Thanks

Update, Example:

Column A:

Jennifer__DoesSomething__inaCity

Column B:

2

Result now:

Jennifer__DoesSomething__inaCity__2

Desired result:

Jennifer__2__DoesSomething__inaCity

The strings Jennifer, DoesSomething, inaCity change and are not the same length. Only the delimiter stays the same. I want to paste after the first delimiter.

Thanks !

Upvotes: 0

Views: 54

Answers (1)

Sotos
Sotos

Reputation: 51592

Here is an idea. Using sub we only replace the first seen pattern. So using mapply we replace all the numbers in one column with their corresponding strings on the second column.

mapply(function(x, y) sub('__', paste0('__', y, '__'), x), df$v1, df$v2)

#     atsfs__dsfgg__sdgsdg          eeee__FFFF__GGGG 
#"atsfs__3__dsfgg__sdgsdg"     "eeee__5__FFFF__GGGG" 

DATA

dput(df)
structure(list(v1 = c("atsfs__dsfgg__sdgsdg", "eeee__FFFF__GGGG"
), v2 = c(3, 5)), .Names = c("v1", "v2"), row.names = c(NA, -2L
), class = "data.frame")

Upvotes: 2

Related Questions