Subham Tripathi
Subham Tripathi

Reputation: 2733

Merge two columns in R while replacing when value is not present in other column

i want to merge two columns of my data set, The nature of these two columns are either/or, i.e if a value is present in one column it wont be present in other column. i tried these

temp<-list(a=1:3,b=10:14)
paste(temp$a,temp$b)

output

"1 10" "2 11" "3 12" "1 13" "2 14"

and this

 temp<-list(a=1:3,b=10:14,c=20:25)
 temp<-within(temp,a <- paste(a, b, sep=''))

output

temp$a
[1] "110" "211" "312" "113" "214"

but what i am looking for is to replace the values when they are not present . for example temp$a only have 1:3 and temp$b have 10:14 , i.e two extra values - so i want my answer to be

1_10 2_11 3_12 _13 _14

EDIT -please look that i do not want column c to be concatenated with a and $b

Upvotes: 2

Views: 154

Answers (2)

akrun
akrun

Reputation: 887891

Using stri_list2matrix, we can fill the list elements that have shorter length with '' and use paste.

library(stringi)
do.call(paste, c(as.data.frame(stri_list2matrix(temp, fill='')), sep='_'))
#[1] "1_10" "2_11" "3_12" "_13"  "_14" 

stri_list2matrix(temp, fill='') converts the list to matrix after filling the list elements that are shorter in length with ''. Convert it to data.frame (as.data.frame) and use do.call(paste to paste the elements in each row separated by _ (sep='_').

Update

Based on the edited 'temp', if you are interested only in the first two elements of 'temp'

 do.call(paste, c(as.data.frame(stri_list2matrix(temp[1:2], fill='')),
         sep='_'))
 #[1] "1_10" "2_11" "3_12" "_13"  "_14" 

You can also subset by the names ie. temp[c('a', 'b')]

Upvotes: 4

thelatemail
thelatemail

Reputation: 93938

Expand the length of the shorter vector to match the length of the longer vector, then paste:

paste(c(temp$a,rep("",length(temp$b)-length(temp$a))), temp$b, sep="_")
#[1] "1_10" "2_11" "3_12" "_13"  "_14" 

Upvotes: 1

Related Questions