我无法从 mapply 函数的输出中获取值而不是因子。下面的代码尝试查找特定位置和时间的温度。
now <- Sys.time()
datetime<-as.POSIXct(seq(now, length.out = 5, by = "hours"), tz = "GMT")
location<-c("Chicago","Detroit","New York","Cleveland","Atlanta")
temperature<-c(2,9,4,8,59)
df1 <- data.frame(datetime, location, temperature)
# add 3 hours to System time
now <- Sys.time() + 3*60*60
datetime<-as.POSIXct(seq(now, length.out = 5, by = "hours"), tz = "GMT")
location<-c("Chicago","Cleveland","Chicago","Detroit","Atlanta")
temperature<-c(6,8,3,12,69)
df2 <- data.frame(datetime, location, temperature)
# Data Frame with Location and Time and Temperature data
loc_temp_df <- rbind(df1,df2)
# Add 2 hours to system time
now <- Sys.time() + 2*60*60
datetime<-as.POSIXct(seq(now, length.out = 7, by = "hours"), tz = "GMT")
location<-c("Chicago","Chicago","New York","Atlanta","New York", "Detroit", "Cleveland")
df <- data.frame(datetime, location)
# Function to find temperature at specific location closest to specific time
myfunction <- function(x,y) {
same_location <- loc_temp_df[which(loc_temp_df$location == y),]
time_at_location <- as.POSIXct(same_location$datetime, format = '%Y-%m-%d %H:%M:%S', tz = "GMT")
index <- which.min(abs(difftime(x, time_at_location, "mins")))
same_location[index,]
}
mapply(myfunction, df$datetime, df$location)
当我运行代码时,我会返回因子而不是值。知道如何返回值而不是因子吗?
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
datetime 1436564283 1436564283 1436560683 1436567883 1436560683 1436575083 1436567883
location factor,1 factor,1 factor,1 factor,1 factor,1 factor,1 factor,1
temperature 6 6 4 59 4 12 8
我尝试使用 lapply 但无法让它以相同的方式工作。