Joining Character to Numeric columns

I have two dataframes Table1 and Table2 with primary keys a and b respectively. a is of class
numeric and b is of class character with the unique values shown below. I need to left join Table1 with Table2 on a = b. What will be the best way to change columns class to make them ready for joining?

unique(Table1$a)
"1A" ,"1B","01" ,"02", "05" ,"10" ,"03"

class(a)
"numeric"

unique(Table2$b)
1, 6, 10, 11, 2, 50, 51, NA

class(b)
"character"

Hi there,

Since your Table1$a contains values that can't be expressed in numeric format, I think that the best solution is to transform your Table2$b values from numeric (really: integer) to string. You can do that like this, to get the leading zeros.

sprintf("%02i", Table2$b)

Then join on the resulting string column.

Hope that helps.

2 Likes

Hi, can you provide a reproducible example please ?
see About REPRoducible EXample (reprex)
A reprex makes it much easier for others to understand your issue and figure out how to help.

I don't get the same as you if I try to recreate: a is character and b is numeric

Table1 <- data.frame(
  a = c("1A" ,"1B","01" ,"02", "05" ,"10" ,"03"),
  stringsAsFactors = FALSE
)
Table2 <- data.frame(
  b = c(1, 6, 10, 11, 2, 50, 51, NA),
  stringsAsFactors = FALSE
)

unique(Table1$a)
#> [1] "1A" "1B" "01" "02" "05" "10" "03"
class(Table1$a)
#> [1] "character"
unique(Table2$b)
#> [1]  1  6 10 11  2 50 51 NA
class(Table2$b)
#> [1] "numeric"

Created on 2020-03-24 by the reprex package (v0.3.0.9001)

For joining, you'll need to do some transformation to get the same key (character maybe your common class here)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.