首页 > 解决方案 > 无法在 R-studio 中将 chr 转换为数字

问题描述

当我尝试转换为数值时,我得到了 NA(见下文)

在此处输入图像描述

我应该将这些年度数据框制作成月度数据框。为此,我需要将数字设为数字。当我尝试这样做时,我得到了 NA。有人知道吗?

标签: rdataframe

解决方案


当您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))

推荐阅读