[R] Merging variables

PIKAL Petr petr.pikal at precheza.cz
Mon Jun 6 15:05:22 CEST 2016


Hi

Not sure if this is the most effective or general solution but

Here you get 2 if the value is same in both columns, 1 if it is only in one column and the other is NA and 0 if there is mismatch of values.
temp <- (ds_test[,2] %in% ds_test[,1])+(ds_test[,1] %in% ds_test[,2])

here you get 0 if the value is same or if there is mismatch, 1 if NA is in first column, 2 if it is in second and 3 if in both.
temp2 <- (is.na(ds_test[,2])+2*is.na(ds_test[,1]))

and with combination you get 1 if you want value from first column, 2 if from second, 4 if they are both NA, and -1 if there is mismatch.
temp2 + temp - 1

You could then construct ifelse command to select proper value.

Regards
Petr


> ds_test
  customer.x customer.y
1     Miller     Miller
2      Smith       <NA>
3       <NA>        Doe
4       Bird       Fish
5       <NA>       <NA>
> ds_test+temp
Error in FUN(left, right) : non-numeric argument to binary operator
> (is.na(ds_test[,1])+2*is.na(ds_test[,2]))+temp
[1] 2 3 2 0 5
> (is.na(ds_test[,1])+2*is.na(ds_test[,2]))+temp-2
[1]  0  1  0 -2  3
> (is.na(ds_test[,1])+2*is.na(ds_test[,2]))+temp-1
[1]  1  2  1 -1  4
> is.na(ds_test[,2])+2*is.na(ds_test[,1])
[1] 0 1 2 0 3
> (is.na(ds_test[,2])+2*is.na(ds_test[,1]))+temp-1
[1]  1  1  2 -1  4
> (is.na(ds_test[,2])+2*is.na(ds_test[,1]))+temp-1

> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of
> G.Maubach at weinwolf.de
> Sent: Monday, June 6, 2016 2:30 PM
> To: r-help at r-project.org
> Subject: [R] Merging variables
>
> Hi All,
>
> I merged two datasets:
>
> ds_merge1 <- merge(x = ds_bw_customer_4_match, y =
> ds_zww_customer_4_match,
>   by.x = "customer", by.y = "customer",
>   all.x = TRUE, all.y = FALSE)
>
> R created a new dataset with the variables customer.x and customer.y. I
> would like to merge these two variable back together. I wrote a little function
> (code can be run) for it:
>
> -- cut --
>
> customer.x <- c("Miller", "Smith", NA,    "Bird", NA)
> customer.y <- c("Miller",  NA,     "Doe", "Fish", NA)
> ds_test <- data.frame(customer.x, customer.y, stringsAsFactors = FALSE)
>
> t_merge_variables <-
>   function(dataset,
>            var1,
>            var2,
>            merged_var) {
>
>     # Initialize
>     dataset[[merged_var]] = rep(NA, nrow(dataset))
>     dataset[["mismatch"]] = rep(NA, nrow(dataset))
>
>     for (i in 1:nrow(dataset)) {
>
>       # Check 1: var1 missing, var2 missing
>       if (is.na(dataset[[i, var1]]) &
>           is.na(dataset[[i, var2]])) {
>         dataset[["mismatch"]] <- 1  # var1 & var2 are missing
>
>       # Check 2: var1 filled, var2 missing
>       } else if (!is.na(dataset[[i, var1]]) &
>                  is.na(dataset[[i, var2]])) {
>         dataset[[i, merged_var]] <- dataset[[i, var1]]
>         dataset[["mismatch"]] <- 0
>
>       # Check 3: var1 missing, var2 filled
>       } else if (is.na(dataset[[i, var1]]) &
>                  !is.na(dataset[i, var2])) {
>         dataset[[i, merged_var]] <- dataset[[i, var2]]
>         dataset[["mismatch"]] <-  0
>
>       # Check 4: var1 == var2
>       } else if (dataset[[i, var1]] == dataset[[i, var2]]) {
>       dataset[[i, merged_var]] <- dataset[[i, var1]]
>       dataset[["mismatch"]] <- 0
>
>       # Leftover: var1 != var2
>       } else {
>         dataset[[i, merged_var]] <- NA
>         dataset[["mismatch"]] <- 2  # var1 != var2
>       }  # end if
>     }  # end for
>     return(dataset)
> }
>
> ds_var_merge1 <- t_merge_variables(dataset = ds_test,
>   var1 = "customer.x",
>   var2 = "customer.y",
>   merged_var = "customer")
>
> ds_var_merge1
>
> -- cut --
>
> It is executed without error but delivers the wrong values in the variable
> "mismatch". This variable is always 1 although it should be NA, 1 or 2
> respectively.
>
> Can you tell me why the variable is not correctly set?
>
> Kind regards
>
> Georg
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.


More information about the R-help mailing list