【问题标题】:Combine list of data frames with one column of characters将数据框列表与一列字符组合
【发布时间】:2015-10-22 05:25:14
【问题描述】:

我正在学习获取、清理和组合数据。我很困惑为什么在循环中rbind 命令会返回 10 个数据,而不是像我手动组合(i by i)时预期的 30 个数据。

library(XML)
mergeal <- NULL 
tabnums <- 3
for (i in 1:length(tabnums)) {
bnn <- paste0("http://www.ngchanmau.com/listing_browse.php?cur_page=", 
              tabnums[i], "&&coming=22-Oct-2015&coming=22-Oct-2015")
tem <- readHTMLTable(bnn, header=T, stringsAsFactors=F)
#data cleaning
ff <- tem[8]   #wanted data
ff1 <- as.data.frame(ff)
ff2 <- ff1[ , 1]         #get 1st col data only
ff3 <- unique(ff2)
ff4 <- ff3[c(2,5:13)]    #wanted list only
#merging dataset
mergeal <- rbind(mergeal, ff4)
}

我尝试过使用listrbind list of data frames with one column of characters and numerics,但仍然得到与上面相同的结果。感谢我错过的任何帮助,谢谢。

【问题讨论】:

  • 您只使用1:length(tabnums) 迭代一次。也许你的意思是1:tabnums?如果是这样,请使用 i 代替 tabnums[i]
  • 谢谢!你说得对,我是初学者。 1:tabnums 做到了。这很有帮助,谢谢。

标签: r rbind


【解决方案1】:

我很无聊,所以我清理了数据。

library(plyr)
library(XML)
library(dplyr)
library(magrittr)
library(stringi)
library(tidyr)
library(lubridate)

answer = 
  data_frame(tabnums = 1:3) %>%
  group_by(tabnums) %>%
  do(.$tabnums %>%
       paste0("http://www.ngchanmau.com/listing_browse.php?cur_page=", 
              ., "&&coming=22-Oct-2015&coming=22-Oct-2015") %>%
       readHTMLTable(header = T, stringsAsFactors = F) %>%
       extract2(8)) %>%
  ungroup %>%
  select(V1) %>%
  distinct %>%
  mutate(V1 = 
           V1 %>%
           stri_replace_all_fixed("Â", "\n") %>%
           stri_replace_all_fixed("Type:", "\nType:") %>%
           stri_replace_all_fixed("Time:", "\nTime:") %>%
           stri_replace_all_fixed("Area:", "\nArea:") %>%
           stri_split_fixed("\n")) %>%
  unnest(V1) %>%
  mutate(V1 = V1 %>% stri_trim) %>%
  filter(V1 %>% stri_detect_regex("^There are currently") %>% `!`) %>%
  filter(V1 != "") %>%
  separate(V1, c("variable", "value"), sep = ":", fill = "left") %>%
  mutate(variable = variable %>% mapvalues(NA, "Description"),
         ID = variable %>% `==`("Description") %>% cumsum) %>%
  spread(variable, value) %>%
  mutate(Area = Area %>% extract_numeric,
         Price = Price %>% extract_numeric,
         Datetime = 
           Time %>% 
           stri_replace_all_fixed("a.m.", "am") %>%
           stri_replace_all_fixed("p.m.", "pm") %>%
           paste(Date, .) %>%
           dmy_hm) %>%
  select(-Date, -Time)

【讨论】:

  • 尝试了您的建议,但出现了错误(我猜是在清理阶段),我错过了哪个库。我加载了:XML、dplyr、magritt、stringi、tidyr。
  • 对不起,我没有包括图书馆!我现在已经添加了它们,并对代码进行了一些编辑。 plyr 是您缺少的那个。确保在 dplyr 之前加载 plyr。
猜你喜欢
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2020-03-29
  • 2017-07-07
  • 2021-04-11
相关资源
最近更新 更多