R错误“不能合并< character>和< double>?

wj8zmpe1  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(408)

我和我的团队正在处理的数据集有问题。当尝试将几个变量mutate转换为一个新变量(名为EU)时,会弹出以下错误:

[Error: Problem with 'mutate()` input `EU`.
x Can't combine `...` <character> and `..2` <double>.]

字符串
我应该注意到,我的团队和我都得到了这个问题,但并不总是在脚本的同一部分。我们都更新了我们的软件来匹配,它似乎仍然发生。
有人知道怎么解决吗??感谢您的任何建议!我们边走边学:)

lsmepo6l

lsmepo6l1#

重现问题:

library(tidyverse)

df1 <- tibble(col = c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"))
df2 <- tibble(col = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
bind_rows(df1, df2)

Error in `bind_rows()`:
! Can't combine `..1$col` <character> and `..2$col` <double>.
Run `rlang::last_trace()` to see where the error occurred.

字符串

说明

当您尝试合并字符类型值的列(例如,"hello world"),其中一列是双类型值(例如100)。

解决方案

找到有问题的列,删除它们,或者转换它们,使它们具有相同的格式:

df3 <- tibble(col = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

df3 %>% 
  mutate(col = as.numeric(col)) %>% 
  bind_rows(df2) # works, returns a column of doubles

df2 %>% 
  mutate(col = as.character(col)) %>%
    bind_rows(df3) # works, returns a column of characters

查找不匹配列

下面的函数查找df1中的列,这些列在df2中,但不具有相同的列类型:

compare_df_col_types <- function(df1, df2) {
  t1 <- df1 %>% 
    map_df(class) %>%
    pivot_longer(everything(), names_to = "df1_cols", values_to = "df1_class")
    t2 <- df2 %>%
    map_df(class) %>%
    pivot_longer(everything(), names_to = "df2_cols", values_to = "df2_class")
    comparison <- t1 %>%
        left_join(t2, by = c("df1_cols" = "df2_cols")) %>%
        filter(df1_class != df2_class)
    return(comparison)
}

相关问题