我无法从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但无法以相同的方式使用它。
答案 0 :(得分:1)
您可以使用Map
中的SIMPLIFY=FALSE
或mapply
将其保留为list
,然后rbind
。
do.call(rbind,Map(myfunction, df$datetime, df$location))
或者
do.call(rbind, mapply(myfunction, df$datetime, df$location, SIMPLIFY=FALSE))