r - How to return values from mapply with factors function arguments and output -


i having trouble getting values instead of factors output of mapply function. code below tries find temperature @ particular location , time.

now <- sys.time()  datetime<-as.posixct(seq(now, length.out = 5, = "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 system time <- sys.time() + 3*60*60  datetime<-as.posixct(seq(now, length.out = 5, = "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 location , time , temperature data loc_temp_df <- rbind(df1,df2)  # add 2 hours system time <- sys.time() + 2*60*60  datetime<-as.posixct(seq(now, length.out = 7, = "hours"), tz = "gmt") location<-c("chicago","chicago","new york","atlanta","new york", "detroit", "cleveland")  df <- data.frame(datetime, location)  # function find temperature @ specific location closest 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) 

when run code factors returned instead of values. idea how can return values instead of factors?

  [,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   

i tried using lapply not work in same way.

you can use either map or simplify=false in mapply keep list , rbind.

 do.call(rbind,map(myfunction, df$datetime, df$location)) 

or

 do.call(rbind, mapply(myfunction, df$datetime, df$location, simplify=false)) 

Comments