What do you think of assigning NA to new column before a loop? Is it consider a best practice ? Is there a more elegant way to do this?
I discovered don't assign NA value to columns before fill them with a loop can cause some troubles, specially on rows where API can't bring an answer: it fill the row with the data from the previous line...
Can you please help?
Url <- c("https://www.r-project.org/","https://cran.r-project.org/")
df <- data.frame(Url)
URL_row <- nrow(df)
df$PageSpeed_Score <- NA
df$PageSpeed_NumberResources <- NA
df$PageSpeed_NumberHosts <- NA
for (i in 1:URL_row) {
url_to_check <- as.character(df[i, "Url"])
print(url_to_check)
PageSpeed_APIrequest <- paste("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=", url_to_check,"&strategy=desktop", sep = "")
PageSpeed_APIrequest <- fromJSON(PageSpeed_APIrequest)
df$PageSpeed_Score[i] <- PageSpeed_APIrequest$rule$SPEED
df$PageSpeed_NumberResources[i] <- PageSpeed_APIrequest$pageStats$numberResources
df$PageSpeed_NumberHosts[i] <- PageSpeed_APIrequest$pageStats$numberHosts
}
The only (small) issue with NA
is that it is of type logical.
typeof(NA)
It might be better to use NA_character_
or NA_real_
(etc.) depending on the expected type of the column. Not a big deal because mutability in R, though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.