admin管理员组文章数量:1291102
I have a function that works perfectly, I just don't quite understand why and how.
Basically, the function loops through a list, extracts values, assigns these values to variables, creates a dataframe with these variables and then returns the dataframe, like so (I omitted a previous code block where the data are queried from the Internet and formatted into lists):
f <- function(lists) {
for (list in lists) {
v1 <- list$value1
v2 <- list$value2
v3 <- list$value3
}
df <- data.frame(V1 = v1,
V2 = v2,
V3 = v3)
return(df)
}
When I provide three lists c(list1, list2, list3)
containing values v1_1, v1_2, v_1_3, v2_1...
etc. as an input, I get
V1 V2 V3
v1_1 v2_1 v3_1
v1_2 v2_2 v3_3
v1_3 v2_3 v3_3
i.e. a dataframe of the values the function extracted, where the values of each list are added as a row to the dataframe.
Which is exactly what I wanted, but I don't really understand how the dataframe knows to add the values per list as a row, when there is only an assignment operator and not rbind() or a similar function. If I create a dataframe in the console and then assign more values to it, I of course overwrite it. Why does this work in a function?
Edit: I added the actual code here:
get_weather_forecast <- function(city_names){
for (city_name in city_names) { #this extracts the data from Open Weather Map
forecast_url <- '.5/forecast'
forecast_query <- list(q = city_name, appid = api_key, units = "metric")
response <- GET(forecast_url, query = forecast_query)
json_list <- content(response, as="parsed")
results <- json_list$list
for(result in results) {
city <- c(city, city_name)
weather <- c(weather, result$weather[[1]]$main)
visibility = c(visibility, result$visibility)
temp <- c(temp, result$main$temp)
temp_min <- c(temp_min, result$main$temp_min)
temp_max <- c(temp_max, result$main$temp_max)
pressure <- c(pressure, result$main$pressure)
humidity <- c(humidity, result$main$humidity)
wind_speed <- c(wind_speed, result$wind$speed)
wind_deg <- c(wind_deg, result$wind$deg)
forecast_datetime <-c(forecast_datetime, result$dt_txt)
}
df <- data.frame(CITY = city,
WEATHER = weather,
VISIBILITY = visibility,
TEMPERATURE = temp,
MIN_TEMP = temp_min,
MAX_TEMP = temp_max,
PRESSURE = pressure,
HUMIDITY = humidity,
WIND_SPEED = wind_speed,
WIND_DEG = wind_deg,
FORECAST_DATE = forecast_datetime)
return(df)
}
本文标签: rHow does a loop function add rows to a dataframeStack Overflow
版权声明:本文标题:r - How does a loop function add rows to a dataframe? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741510571a2382583.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论