我正在寻找将数据帧列值分配到函数中特定位置的方向,然后循环或创建一系列对象以绑定到更长的表中。
示例数据
a = c("17","17","29")
b = c("133","163","055")
data.frame(a, b)手工操作..。
library(zipcodeR)
T1 <- search_fips("17", "133")
T2 <- search_fips("17", "163") 
T3 <- search_fips("29", "055")
TT <- list(T1, T2, T3)
CZ_zips <- rbindlist(TT, use.names=TRUE, fill=TRUE)希望a将a和b列读入函数中的一个固定位置,以创建一系列向量或数据帧,然后将其绑定到一个较长的表中。
search_fips函数从a= state和b=县的人口普查数据中提取。包是zipcodeR。
发布于 2022-02-18 20:00:29
一种简单的方法是将search_fips()函数封装到lapply函数中,而rest保持不变。
library(zipcodeR)
a = c("17","17","29")
b = c("133","163","055")
df<-data.frame(a, b)
output <-lapply(1:nrow(df), function(i) {
   search_fips(df$a[i], df$b[i])
})
  
answer <- dplyr::bind_rows(output)发布于 2022-02-18 20:01:10
下面是您可能需要在函数中添加的一个循环:
library(dplyr)
library(zipcodeR)
my_list <- list()
for (i in 1:nrow(df)) {
  my_list[i] <- search_fips(df$a[i], df$b[i])
  
}
new_df <- bind_rows(my_list)
bind_rows(my_list)发布于 2022-02-18 20:32:37
使用rowwise
library(dplyr)
library(tidyr)
library(zipcodeR)
out <- df %>% 
 rowwise %>% 
 mutate(result = list(search_fips(a, b))) %>%
 ungroup %>% 
 unnest(result)-output
> head(out, 2)
# A tibble: 2 × 26
  a     b     zipcode zipcode_type major_city post_office_city common_city_list county        state   lat   lng timezone radius_in_miles area_code_list
  <chr> <chr> <chr>   <chr>        <chr>      <chr>                      <blob> <chr>         <chr> <dbl> <dbl> <chr>              <dbl>         <blob>
1 17    133   62236   Standard     Columbia   Columbia, IL           <raw 20 B> Monroe County IL     38.4 -90.2 Central                7     <raw 15 B>
2 17    133   62244   Standard     Fults      Fults, IL              <raw 17 B> Monroe County IL     38.2 -90.2 Central                7     <raw 15 B>
# … with 12 more variables: population <int>, population_density <dbl>, land_area_in_sqmi <dbl>, water_area_in_sqmi <dbl>, housing_units <int>,
#   occupied_housing_units <int>, median_home_value <int>, median_household_income <int>, bounds_west <dbl>, bounds_east <dbl>,
#   bounds_north <dbl>, bounds_south <dbl>数据
df <- structure(list(a = c("17", "17", "29"), b = c("133", "163", "055"
)), class = "data.frame", row.names = c(NA, -3L))https://stackoverflow.com/questions/71179048
复制相似问题