简体   繁体   中英

Loop output in R Dataframe

I am new to R and looking to get for loop output in each iteration in one dataframe. Below is the code, where I am trying to get data in Results dataframe

for (i in 1:nrow(base_data)) {
LCS1 <- expand.grid(STREET=base_data$STREET[1:nrow(base_data)],REF_STREET=base_data$STREET[i])
LCS$LCS_stringdist=stringdist(LCS$STREET,LCS$Name1,method="lcs")
Results <- head(LCS[order(LCS$LCS_stringdist),],20) 
}

I think the easiest way is to assign to items of a list and then bind into a data frame at the end.

results_list = list()

for (i in 1:nrow(base_data)) {
  LCS1 <- expand.grid(STREET=base_data$STREET[1:nrow(base_data)],REF_STREET=base_data$STREET[i])
  LCS$LCS_stringdist=stringdist(LCS$STREET,LCS$Name1,method="lcs")
  results_list[[i]] <- head(LCS[order(LCS$LCS_stringdist),],20) 
}

Results = do.call(rbind, results_list)

## faster options in other packages
Results = dplyr::bind_rows(results_list)
Results = data.table::rbindlist(results_list)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM