I would like to take the output of this loop and append it in a dataframe. Any suggestion would be helpful
Hi there,
Looking at the function it is not clear what you are trying to do here, but chances are you don't even need a loop with IF statement if you just want to extract or rearrange data...
Next time try to generate a reprex instead of using a screenshot. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:
That said, here are two generic examples of appending things to a data frame, the first one just using base R, the other one using tidyverse functions.
#Base R
myData = data.frame(
a = character(),
b = numeric()
)
for(i in 1:10){
if(i %% 2 == 0){
myData[nrow(myData)+1,] = list(i, runif(1))
}
}
myData
#> a b
#> 1 2 0.5419549
#> 2 4 0.8368228
#> 3 6 0.2262199
#> 4 8 0.1070023
#> 5 10 0.8860279
#Tidyverse mapping
library(tidyverse)
map_df(1:10, function(i){
if(i %% 2 == 0){
tibble(a = i, b = runif(1))
}
})
#> # A tibble: 5 x 2
#> a b
#> <int> <dbl>
#> 1 2 0.268
#> 2 4 0.865
#> 3 6 0.269
#> 4 8 0.701
#> 5 10 0.246
Created on 2021-05-03 by the reprex package (v2.0.0)
Hope this helps,
PJ
Thanks, PJ. Here's a better visual. I'm trying to populate the data frame with the for loop out put. All I get when I run is the last variable in the dataframe that qualifies.
HDL_uip <- data.frame()
for(i in 1:nrow(under_income_pop)){
HDL_county <- under_income_pop[i, "county"]
L_uip <- under_income_pop[i,"Lcount"]
HD_uip <- under_income_pop[i, "HDcount"]
if(L_uip == 0 | HD_uip == 0){
HDL_uip <- data.frame(HDL_county, L_uip, HD_uip)
}
}
View(HDL_uip)
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.