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