bind_rows列表中,即使 class() 不同

bind_rows in a list even though the class() is different

提问人:Seyma Kalay 提问时间:5/5/2023 最后编辑:zx8754Seyma Kalay 更新时间:5/5/2023 访问量:185

问:

我在下面有一个列表,我不想做的是更改 .代码应更改 class(category) 并在对象中为其分配类别。如何解决这个问题?提前非常感谢。class(Category)df2list()

df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples" )
df2 <- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1),  Category= seq(0.1,0.4,0.1))
df3 <- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1),  Category= "Apples3")

list1 <- list(df1, df2, df3);list1
bind_rows(list1)

Error in `bind_rows()`:
! Can't combine `..1$Category` <character> and `..2$Category` <double>.
Run `rlang::last_trace()` to see where the error occurred.
r dplyr tidyr 数据操作 整洁

评论

2赞 benson23 5/5/2023
在 R 中,DataFrame 不能在同一列中具有多个值类。因此,您不能在同一列中同时使用数字(例如)和字符(例如,)。df2$Categorydf1$Categorydf3$Category

答:

1赞 akrun 5/5/2023 #1

我们可以将所有列转换为,然后自动更改类型charactertype.convert

library(purrr)
library(dplyr)
 map_dfr(list1, ~ .x %>% 
  mutate(across(everything(), as.character))) %>% 
  type.convert(as.is= TRUE)

-输出

# A tibble: 12 × 5
   ID    valueA Category valueB valueC
   <chr>  <dbl> <chr>     <dbl>  <dbl>
 1 A1       0.1 Apples     NA     NA  
 2 A2       0.2 Apples     NA     NA  
 3 A3       0.3 Apples     NA     NA  
 4 A4       0.4 Apples     NA     NA  
 5 A5      NA   0.1         0.1   NA  
 6 A6      NA   0.2         0.2   NA  
 7 A7      NA   0.3         0.3   NA  
 8 A8      NA   0.4         0.4   NA  
 9 A9      NA   Apples3    NA      0.1
10 A10     NA   Apples3    NA      0.2
11 A11     NA   Apples3    NA      0.3
12 A12     NA   Apples3    NA      0.4

或者我们可以nest

map_dfr(list1, ~ .x %>% nest(data = Category))

-输出

# A tibble: 12 × 5
   ID    valueA data             valueB valueC
   <chr>  <dbl> <list>            <dbl>  <dbl>
 1 A1       0.1 <tibble [1 × 1]>   NA     NA  
 2 A2       0.2 <tibble [1 × 1]>   NA     NA  
 3 A3       0.3 <tibble [1 × 1]>   NA     NA  
 4 A4       0.4 <tibble [1 × 1]>   NA     NA  
 5 A5      NA   <tibble [1 × 1]>    0.1   NA  
 6 A6      NA   <tibble [1 × 1]>    0.2   NA  
 7 A7      NA   <tibble [1 × 1]>    0.3   NA  
 8 A8      NA   <tibble [1 × 1]>    0.4   NA  
 9 A9      NA   <tibble [1 × 1]>   NA      0.1
10 A10     NA   <tibble [1 × 1]>   NA      0.2
11 A11     NA   <tibble [1 × 1]>   NA      0.3
12 A12     NA   <tibble [1 × 1]>   NA      0.4

1赞 zx8754 5/5/2023 #2

我们可以将 Category 列转换为列表,然后进行行绑定,这样我们就可以保留类:

#convert Category column into list class
list1 <- lapply(list(df1, df2, df3),
                function(i){ mutate(i, Category = as.list(Category)) })
#then bind
out <- bind_rows(list1)

#check class
class(unlist(out[1, "Category"]))
# [1] "character"
class(unlist(out[5, "Category"]))
# [1] "numeric"