2

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

Juriv
  • 49
  • 1
  • 4
  • 1
    There are some good references for how to make a question more *reproducible* so that we can "play with" the code and data that you have, instead of trying to infer it. Please see https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. One notable thing is that copying what a `data.frame` *looks like* on the console might seem useful, but with your mention of `factor`, that fails, since the representation of factors in a frame is nothing like how the internal data is stored. Thanks! – r2evans Feb 17 '21 at 16:24

2 Answers2

1

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))
redarah
  • 152
  • 7
0

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.

redarah
  • 152
  • 7