首页 > 解决方案 > 为什么在 R 中使用 left_join() 时会出现“无效的 'times' 参数”错误?

问题描述

我有两个 tibbles,我无法弄清楚为什么我在使用left_join它们合并时会出错:

df <- structure(list(animal = c("cat", "dog", "mouse", "rat", 
"pidgeon", "fish"), value = c(-2.71, -2.63, 
-2.66, -6.99, -2.11, -6.44), ID = c("2700", 
NA, NA, "4821", "55117", "NA")), row.names = c(NA, -5L
), class = c("tbl_df", "tbl", "data.frame"))

> df
# A tibble: 5 x 3
  animal  value ID   
  <chr>   <dbl> <chr>
1 cat     -2.71 2700 
2 dog     -2.63 NA   
3 mouse   -2.66 NA   
4 rat     -6.99 4821 
5 pidgeon -2.11 55117

new_vals <- structure(list(animal = c("dog", "pidgeon"), ID_new = c("123456", "25255")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

> new_vals
# A tibble: 2 x 2
  animal  ID_new
  <chr>   <chr> 
1 dog     123456
2 pidgeon 25255 


df_new <- left_join(
        df,
        new_vals,
        by = "animal"
    )

Error in rep(x_loc, lengths(y_loc)) : invalid 'times' argument

请问有人能告诉我错误在哪里吗?我感觉我快疯了!

标签: r

解决方案


df在某种程度上被破坏了。

如果您查看structure(.)您提供的输出,您会看到"animal"长度为 6,但结构认为row.names = c(NA, -5L)只有五行。当您查看时df,它确实只显示了 5 行但仍有"fish"显示。

以编程方式修复它:

attr(df, "row.names") <- seq_along(df$animal)
df
# # A tibble: 6 x 3
#   animal  value ID   
# * <chr>   <dbl> <chr>
# 1 cat     -2.71 2700 
# 2 dog     -2.63 <NA> 
# 3 mouse   -2.66 <NA> 
# 4 rat     -6.99 4821 
# 5 pidgeon -2.11 55117
# 6 fish    -6.44 NA   

现在显示六行,连接现在有效。

left_join(df, new_vals, by = "animal")
# # A tibble: 6 x 4
#   animal  value ID    ID_new
#   <chr>   <dbl> <chr> <chr> 
# 1 cat     -2.71 2700  <NA>  
# 2 dog     -2.63 <NA>  123456
# 3 mouse   -2.66 <NA>  <NA>  
# 4 rat     -6.99 4821  <NA>  
# 5 pidgeon -2.11 55117 25255 
# 6 fish    -6.44 NA    <NA>  

(我不知道这是怎么发生的……如果您在其他地方以编程方式阅读了该内容,则应该查看哪些代码在做什么,然后停止执行您所做的事情或报告错误……这永远不会发生。 )


推荐阅读