Error: Can't combine `..1$A` <double> and `..2$A` <factor<ee569>>

Viewed 2068

I would like to use bind_rows() to append two dataframes (by their column headers) but when I run the code I get the Error: Can't combine ..1$A and ..2$A <factor>.

I know I need to convert the factor to double but I don't know how to perform this operation on all columns.

I have approx 500 columns and thus cannot use as.double

One dataframe X is very large (500 columns and 5000 rows) and the other Y rather small (495 columns and only 1 row). The append should be done based on common column header. Basically I want to add the row of Y at the end of X.

Let me know if you need more information.

Thx

2 Answers

You can use across to convert all the columns at once. Here's an example:

library(tidyverse)

# Here I'm just making an example dataframe with 26 columns
dat <- data.frame(letters = letters, n = factor(seq(26))) %>%
  pivot_wider(names_from = "letters", values_from = n)

# If you wanted to change all columns you'd just do:
dat %>% 
  mutate(across(cols_to_change, as.double))

And if you wanted to change a subset of columns (here I do 1-25 as an example), you'd do:

cols_to_change <- colnames(dat)[1:25]

# Use mutate_at to convert all at once
dat %>% 
  mutate(across(cols_to_change, as.double))

TLDR force everything to be a factor.

I was able to reproduce your error by running this:

df1 <- data.frame (A = factor("Retail"), 
                   AA = factor("Automotive"), 
                   PR = factor("Automotive"), 
                   DFI = factor("Tech" )) 
df2 <- data.frame(A = 1, AA = 2, PR = 3, DFI = 4)

bind_rows(df1, df2)

Which gives me:

Error: Can't combine `..1$A` <character> and `..2$A` <double>.

I fix it by doing:

df2 <- mutate(df2, across(everything(), as.factor))
bind_rows(df1, df2)

And that works.

Related