You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言merge函数报错:无法将closure类型转为any类型向量

问题解决与代码优化

报错原因

你遇到的cannot coerce type 'closure' to vector of type 'any'错误,根源是merge函数中by = Date``的写法错误:R中Date是基础包自带的函数(类型为closure),这里你需要指定的是数据框的列名,应该用双引号或单引号包裹,而非反引号。

修正并优化后的代码

结合你整合Date、收盘价(或调整收盘价)、Dividend的需求,同时优化为自动获取最新数据(无需每月手动修改时间戳),代码如下:

library(tidyverse)
library(glue) # 用于拼接动态URL

D_NVDY_Pull <- function() {
  # 生成动态时间戳:起始时间设为1年前,结束时间为当前系统时间
  period1 <- as.integer(Sys.time() - 365*24*60*60)
  period2 <- as.integer(Sys.time())
  
  # 拉取分红数据,仅保留需要的列
  NVDY_div <- read_csv(glue("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1={period1}&period2={period2}&interval=1d&events=dividends&includeAdjustedClose=true")) %>%
    select(Date, Dividend)
  
  # 拉取行情数据,保留日期、收盘价、调整收盘价
  NVDY_price <- read_csv(glue("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1={period1}&period2={period2}&interval=1d&events=history&includeAdjustedClose=true")) %>%
    select(Date, Close, `Adj Close`)
  
  # 按日期左连接,确保所有行情日期都保留,无分红的日期自动填充NA
  NVDY_combined <- left_join(NVDY_price, NVDY_div, by = "Date")
  
  return(NVDY_combined)
}

# 调用函数获取整合后的数据
final_data <- D_NVDY_Pull()

核心优化点

  • 替换merge为left_join:更适配tidyverse生态,且能保留所有行情日期,无分红记录的日期会自动将Dividend设为NA,比默认的内连接更贴合你的需求。
  • 动态时间戳:利用Sys.time()自动生成当前时间的时间戳,每月运行时自动拉取最新数据,无需手动修改URL中的时间参数。
  • 提前筛选列:用select()只保留需要的字段,减少数据冗余,提升代码运行效率。

内容的提问来源于stack exchange,提问作者TheNautical_Sailor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:47:39