r - 无法在 R-studio 中将 chr 转换为数字
解决方案
当您unlist()
使用数据框时,它会将其转换为向量。这是我可以从您的帖子中看到的几行数据(变量名称较短)。
TBS <- tibble::tibble(
desc = c("1934-01", "1934-02"),
rate = c("0.72", "0.6")
)
unlist(TBS)
# desc1 desc2 rate1 rate2
# "1934-01" "1934-02" "0.72" "0.6"
当您as.numeric()
在该向量上执行此操作时,它会将日期变为丢失。我认为这就是您的 RStudio 窗口中上面的输出向我们展示的内容。
as.numeric(unlist(TBS))
# [1] NA NA 0.72 0.60
您最好将变量固定在数据框中,如下所示:
library(zoo)
library(lubridate)
library(dplyr)
TBS <- TBS %>%
mutate(desc = as.yearmon(desc),
year = year(desc),
rate = as.numeric(rate))
TBS
# A tibble: 2 x 3
# desc rate year
# <yearmon> <dbl> <dbl>
# 1 Jan 1934 0.72 1934
# 2 Feb 1934 0.6 1934
然后你可以做你多年来需要的任何事情(例如,平均)。如果它只是一个直线平均值,你可以做到。
TBS %>%
group_by(year) %>%
summarise(mean_rate = mean(rate))
推荐阅读
- kubernetes - 如何移除已移除节点的 pod
- java - 在更改片段上杀死线程
- mysql - Mysql查询:选择先加入或默认
- javascript - javascript中的标签部分在codeigniter框架php中不起作用
- python - 在 Django 中为无序列表创建模型
- java - 如何使 PDFormField 的内容居中?
- microsoft-graph-api - Outlook 图形 API 是否缓存事件?
- pyspark - 窗口上的总行数
- java - 需要有关 Spring Boot Kafka Stream Binder Application 错误的建议
- ionic-framework - Ionic Appflow:免费计划的实时更新