在填充数据之前,我问了两个问题:
(Ⅰ)Question_one (Ⅱ)Question_two
按照我的建议,它几乎成功了,但仍然有一个警告和一个错误。
我使用以下代码从Excel导入数据。 (您可以在this Google Drive website中下载此文件):
#read form clipborad, which is copied in "Example_a.xlsx"
# read dt_A
dt_A <- read.delim("clipboard",header=TRUE)
# read dt_B
dt_B <- read.delim("clipboard",header=TRUE)
然后,将字符更改为“日期”格式:
#Change "Date" to date format
as.POSIXct(dt_A$Date, format="%m/%d/%Y %H:%M")
as.POSIXct(dt_B$Date, format="%m/%d/%Y %H:%M")
但是,当我使用“完成”(由AntoniosK建议)填写缺少的日期时,会出现警告。
library(tidyverse)
# complete dates of data B using dates of data A
df <- dt_B %>% complete(Date = dt_A[1])
警告是:
Warning message:
Column `Date` joining factors with different levels, coercing to character vector
但是,df似乎符合预期(图1)。然后,我将忽略此警告,并使用Jay Achar建议的代码:
library(dplyr)
library(lubridate)
df %>%
mutate(B_Value = ifelse(is.na(B_Value),
lag(B_Value, 1) + (lead(B_Value, 1) - lag(B_Value, 1)) *
as.numeric(difftime(Date, lag(Date, 1))) /
as.numeric((difftime(lead(Date, 1), Date) + difftime(Date, lag(Date, 1)))),
B_Value)) %>%
mutate(B_Value = round(B_Value, 2))
发生错误:
Error in mutate_impl(.data, dots) :
Evaluation error: character string is not in a standard unambiguous format.
您能教我为什么会有警告和错误吗?