r - 为什么在 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
请问有人能告诉我错误在哪里吗?我感觉我快疯了!
解决方案
你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>
(我不知道这是怎么发生的……如果您在其他地方以编程方式阅读了该内容,则应该查看哪些代码在做什么,然后停止执行您所做的事情或报告错误……这永远不会发生。 )
推荐阅读
- matplotlib - 没有文本渲染的 matplotlib SVG 导致尺寸错误
- c# - 如何关闭 MahApps Button 透明效果?
- postgresql - 复合 FK 引用原子 PK + 非唯一属性
- reactjs - 尝试使用 react-bootstrap 包创建带有下拉菜单的侧边栏
- node.js - 如何使用 javascript neo4j 驱动程序处理死锁?
- .net - 在 WinForms 中托管应用程序时 WPF Telerik 控件消失
- go - 使用 Error.Is 函数比较动态错误消息
- python - Python中的狄拉克三角洲和FFT
- airflow-scheduler - 一段时间后,Apache Airflow 调度程序未运行
- javascript - 移动设备上带有 html2canvas 的画布视口