logo
down
shadow

Use GET function to run results from a loop


Use GET function to run results from a loop

By : Bradford Harrison
Date : October 16 2020, 03:08 PM
it should still fix some issue Whenever I see a problem that says "1 or more" of something, I tend to think about doing something once and iterating over all items in a vector or list. You started thinking in that way, but in your loop, you assign over URL each time and only save the last one. Even had you saved all of the URLs, though, GET only retrieves one at a time, so you need to iterate that function as well.
This demo is mostly concept with no real proof that it works. Because you included an actual API key in your question, it has been exhausted. (You probably want to delete it from the question.) Regardless, I'm somewhat confident the concept works of applying functions to a list of things, so though I haven't verified that you get a huge data.frame out of it, perhaps I'll get lucky.
code :
z <- expand.grid(lon = seq(-124.4531, -68.02734, by=5.9180),
                 lat = seq(25.7998, 49.0090, by=5.6667))
head(z)
#         lon     lat
# 1 -124.4531 25.7998
# 2 -118.5351 25.7998
# 3 -112.6171 25.7998
# 4 -106.6991 25.7998
# 5 -100.7811 25.7998
# 6  -94.8631 25.7998
mapply(function(x,y,z) x+y-z,
       c(1,2,3,4), c(5,6,7,8), c(9,10,11,12))
URLs <- mapply(sprintf,
               list("https://maps.googleapis.com/maps/api/place/radarsearch/json?location=%s,%s&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"),
               z$lat, z$lon)
sprintf("https...", z$lon[1], z$lon[2])
sprintf("https...", z$lon[2], z$lon[2])
# ...
sprintf("https...", z$lon[50], z$lon[50])
(URLs <- head(URLs)) # doing this for a simpler demo, since I don't need all 50
# [1] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-124.4531,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"
# [2] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-118.5351,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"
# [3] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-112.6171,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"
# [4] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-106.6991,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"
# [5] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-100.7811,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU"
# [6] "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-94.8631,25.7998&radius=50000&name=MetroPCS&key=AIzaSyA3u4HwTGiUsHP7FNUKkjbYcHHe1xFBDTU" 
HTMLs <- lapply(URLs, GET)
HTMLs[1]
# [[1]]
# Response [https://maps.googleapis.com/maps/api/place/radarsearch/json?location=-124.4531,25.7998&radius=50000&name=MetroPCS]
#   Date: 2017-10-18 03:23
#   Status: 200
#   Content-Type: application/json; charset=UTF-8
#   Size: 141 B
# {
#    "error_message" : "This service requires an API key.",
#    "html_attributions" : [],
#    "results" : [],
#    "status" : "REQUEST_DENIED"
# }
contents <- lapply(HTMLs, content, "text")
myDataFrames <- lapply(contents, jsonlite::fromJSON)
myDataFrame <- do.call(rbind.data.frame, c(myDataFrames, list(stringsAsFactors = FALSE)))
myDataFrames <- lapply(URLs, function(u) {
  html <- GET(u)
  cont <- cont(html, "text")
  jsonlite::fromJSON(cont)
})


Share : facebook icon twitter icon
Passing to a MATLAB function arguments from an array and saving function results using FOR-loop

Passing to a MATLAB function arguments from an array and saving function results using FOR-loop


By : wajeed syed
Date : March 29 2020, 07:55 AM
it helps some times I need to run a specific function 4 times, each time passing new arguments to it (getting them from array) and save the result in another array after each iteration. , You can avoid using the loop altogether:
code :
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]

result = 2 * x .* y .* z ./ 1000;
How to call another function in the function and loop the results by storing in the variable?

How to call another function in the function and loop the results by storing in the variable?


By : BianWenbo
Date : March 29 2020, 07:55 AM
I hope this helps . I would like to ask an question about the usage of function in PHP. How can I call another function in PHP? , see this:
code :
      $Table = "<table border=1>";
         $Table .= "<tr>"; 
$Tab="";
         function bookingHour($Tab){
            for($i=0;$i<6;$i++){ //loop the hour 1-6 and display the content by function booking()
            echo $i;
                $Tab .= "<td align=center>" . booking($array, $rmNum, $dateTime) . "</td>";// otherwise table tag will repeate multiple time and won't display correctly.
            }
            return $Tab;
         }
        $Table.=$Tab;
         $Table .= "</tr>";
         $Table .= "</table><br>";
         echo $Table;
Should I be returning DB results inside the function or loop through the results outside the function?

Should I be returning DB results inside the function or loop through the results outside the function?


By : Alireza
Date : March 29 2020, 07:55 AM
To fix this issue There aren't any specific security issues with your code that I can see, but best practice right now is to use the MVC - model, view, controller - design pattern. See here. Or the MVP - model, view, presenter - design pattern. See here. Both are very similar.
Using one of these patterns has many benefits but the biggest ones in my opinion are code readable, portability, and reusability. It may also speed things up as well.
how to store results into a for loop of matrices applying a function at each step of the loop?

how to store results into a for loop of matrices applying a function at each step of the loop?


By : Vishnu Vardhan
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm trying to apply a function to a matrix inside a for loop. The output should also be a matrix that changes at each step of the loop. The codes below explains my problem: , There are two easy ways to go for:
1- Using get and assign:
code :
# How get and assign work: 

x0 = 10 
get(paste0("x", 0)) # get the variable passed as a string argument - returns 10
assign(paste0("x", 0), 20) # assign 20 to x
print(x0) #20


# And.. the recursion 

x0 = 2 # recursive initialization

for(i in 1:5) {
  previousValue = get(paste0("x", i-1))
  thisValue = previousValue * 2 
  assign(paste0("x", i), thisValue)
}
x0 = 2 # recursive initialization
myResults = list(x0)

# Now, the recursion!
for(i in 1:5) {
  thisValue = myResults[[i]] 
  nextValue = c(thisValue * 2)  # Some random calculation, use your function instead
  myResults[[i+1]] = nextValue  # Now add to the list 
}
How to repeatedly call a function for each iteration in a loop, get its results then append the results into a slice (Go

How to repeatedly call a function for each iteration in a loop, get its results then append the results into a slice (Go


By : Dawnee
Date : March 29 2020, 07:55 AM
hop of those help? I have the ff: , Just do the loop twice, e.g.
code :
for _, symbol := range distinctSymbols {
        go worker(symbol, stmt1, stmt2, c)
}
for range distinctSymbols {
        symbolsSlice = append(symbolsSlice, <-c)
}
Related Posts Related Posts :
  • Y-Axis positions of barplot and base plot do not match
  • Rolling queue size
  • How to use hist() function with count data as input
  • How to count aggregated data and create different counters?
  • r - prefixing specific column titles in data frame
  • Frequency cross-tabulation in R for categorical variables
  • R: Function to ID duplicated dates and jitter months to get sequential months within a year
  • From a vector of 1 and 0, how to keep only the ones before the first 0?
  • Filter dataframe using global variable with the same name as column name
  • Fill matrix using names with Rcpp
  • Combine data frames by rows in respect to even odd elements
  • Sum selective rows in data.table
  • How to find max of a column within a particular daterange using data.table
  • Can text2vec and topicmodels generate similar topics with suitable parameter settings for LDA?
  • Error in bind_rows_(x, .id) : Column can't be converted from factor to numeric
  • How to incorporate a LUT in a dplyr funs?
  • Create a list where each element is a pair of contiguous members from given vector
  • Why is class considered to be a special case of vector in R?
  • Why is order() faster than sort.list()?
  • R how to ggplot frequency every 2 hours in dataframe
  • Assign two variables to each other without duplicates | Create groups of two in R
  • NULL output from lapply and trycatch
  • Find the values between the range of 100's and their count
  • How to retain date/time format in xtable for an email
  • Copy two column values from one data frame to one column but two rows in another data frame
  • convert from sort of long format to one row expanded
  • How to save a ggcoxzph plot in R?
  • grid.text in a ggplot give an error in plot_grid
  • Convert multiple columns to a existing column
  • Calling API from R to retrieve data
  • Convert a database from MongoDB to a R data frame using Rmongo
  • Parsing a web page with stringr
  • R error: Namespace load failed for in readRDS(nsInfoFilePath)
  • How to pass Thunderforest API key to the R ggspatial package to create a map
  • Get value of named character vector element when name is NA
  • Fastest way to extract date from date time in R
  • Passing Vectors as Arguments in functions R
  • Non-equi join for a group of variables without providing intervals
  • Regression model function (with user selected variables) on subset of data frame
  • Extracting character probabilities that were randomly sampled in R
  • Factors and dummies in R regressions
  • Axis tick marks re positioning in R
  • R: using factor variables in nlme function
  • Make a factor variable out of few data.frame columns
  • Overlay overall distribution graph with segment wise distribution
  • Cross product of vector
  • How to store loop output of each iteration to data frame
  • Acquire factors for each level of a character vector
  • can I estimate a time varying seasonal effect in R with GAMM?
  • SD value not showed in dplyr
  • Use milliseconds in variable Time with R
  • Why does R.predict.svm return a list of the wrong size?
  • ggmap + ggplot will not plot certain values
  • How to stop for loop from printing results in R
  • Restructuring DataFrame Based on Single Column Values
  • How to split data.frame to equal columns
  • Replace NAs in vector (A) with specific values from another vector (B) and force the copied value in vector (B) to NAs
  • How to add an in memory png image to a plot?
  • R: Read in random rows from file using fread or equivalent?
  • selectInput is not updated properly in R Shiny
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com