r - 错误:Tibble 列必须具有一致的长度,只有长度为 1 的值被回收:* 长度 61:列 `y` * 长度 10358:列 `x`
问题描述
我正在尝试使用以下 R 代码绘制冠状病毒在印度与世界其他地区的传播情况,我将 corona_world 作为数据框并从中创建了 daily_confirmed 数据框。我已经消除了变量列 'India' 中的所有 NA 值。但仍然错误说它没有相同的长度。我不明白为什么它不起作用。请帮忙
错误:Tibble 列必须具有一致的长度,只有长度为 1 的值被回收:* 长度 61:列 y * 长度 10358:列 x
daily_confirmed <- corona_world %>%
dplyr::select(Confirmed) %>%
dplyr::mutate(country = dplyr::if_else(corona_world$Country.Region == "India",
"India",
"Rest of the World")) %>%
dplyr::group_by(corona_world$ObservationDate, country) %>%
dplyr::summarise(total = sum(Confirmed, rm.na=TRUE)) %>%
dplyr::ungroup() %>%
tidyr::pivot_wider(names_from = country, values_from = total)
daily_confirmed <- daily_confirmed[-c(1:8),]
daily_confirmed %>%
plotly::plot_ly() %>%
plotly::add_trace(x = ~ corona_world$ObservationDate,
y = ~ India,
type = "scatter",
mode = "lines+markers",
name = "India") %>%
plotly::add_trace(x = ~ corona_world$ObservationDate,
y = ~ Rest of the World,
type = "scatter",
mode = "lines+markers",
name = "Rest of the World") %>%
plotly::layout(title = "",
legend = list(x = 0.1, y = 0.9),
yaxis = list(title = "Number of New Cases"),
xaxis = list(title = "Date"),
hovermode = "compare",
margin = list(b = 10,
t = 10,
pad = 2
))
解决方案
除了代码中的一些拼写错误外,错误是由于映射corona_world$ObservationDate
到x
. 你必须ObservationDate
从daily_confirmed
上映射x
。此外,当使用带有空格的 var 名称时,例如“Rest of the World”,您必须将 var 名称放在反引号中,例如:“y = ~ `Rest of the World`”。
尝试这个。我检查了gapminder数据,所以它应该可以工作。顺便说一句:我还修改了您的代码以使其更简洁:
library(dplyr)
library(tidyr)
library(plotly)
daily_confirmed <- corona_world %>%
#select(Confirmed) %>%
mutate(country = dplyr::if_else(Country.Region == "India",
"India",
"Rest of the World")) %>%
group_by(ObservationDate, country) %>%
summarise(total = sum(Confirmed, rm.na=TRUE)) %>%
ungroup() %>%
pivot_wider(names_from = country, values_from = total)
daily_confirmed <- daily_confirmed[-c(1:8),]
daily_confirmed %>%
plotly::plot_ly() %>%
plotly::add_trace(x = ~ ObservationDate,
y = ~ India,
type = "scatter",
mode = "lines+markers",
name = "India") %>%
plotly::add_trace(x = ~ ObservationDate,
y = ~ `Rest of the World`,
type = "scatter",
mode = "lines+markers",
name = "Rest of the World") %>%
plotly::layout(title = "",
legend = list(x = 0.1, y = 0.9),
yaxis = list(title = "Number of New Cases"),
xaxis = list(title = "Date"),
hovermode = "compare",
margin = list(b = 10,
t = 10,
pad = 2
))
推荐阅读
- python - 合并排序python中的反转数
- android - 设置约束布局的高度是否正确?
- android - Android - 如果用户选择“使用应用程序时”并且应用程序在后台,我可以访问用户的位置吗?
- c# - 正确理解带有委托的 .NET 堆栈跟踪
- cygwin - Cygwin 安装 NS3 问题
- javascript - QR 码扫描器 javascript 模块在没有 HTTPS/安全连接的情况下运行
- javascript - 动态函数调用jquery
- ms-access - MS Access 中的标准
- reactjs - 在 React 中不显示 MongoDB 数据
- c - 如何在 Visual Studio Code 中运行 C 程序?