【问题标题】:Combine filtered data from each files into new data frame将每个文件中的过滤数据合并到新的数据框中
【发布时间】:2018-11-23 09:52:29
【问题描述】:

我想从多个文件中过滤特定的数据行并将其合并到一个数据帧中,因此每次读取新文件时该数据帧都应该增长。我的代码能够遍历所有文件,但只创建最后一个文件的数据框。我可以得到我想要的数据框,而不必先组合每个文件中的所有原始大容量数据吗?请指教。

library(dplyr)
library(ggplot2)
library(tidyverse)
y = 1978
N <- 10
for (i in 1:N) {
  yr = y +(as.numeric(i))
  yr = as.character(yr)
  p <- paste0("c:/Users/Hp/Documents/",yr,".csv")

  #read.csv
  dat <- read.csv(p,header = TRUE, stringsAsFactors = F)
  #filter
  dat_sub <- filter(dat, hght_m > 0)
  dat_sub <- filter(dat_sub, temp_c > 0)
  dat1_sub <- filter(dat_sub, pres_hpa == 1000)
  dat2_sub <- filter(dat_sub, pres_hpa == 925)
  dat3_sub <- filter(dat_sub, pres_hpa == 850)
  dat4_sub <- filter(dat_sub, pres_hpa == 700)
}
all.temp <- rbind(dat1_sub,dat2_sub, dat3_sub,dat4_sub)
ggplot(data = all.temp, aes(x= as.Date(date), y = temp_c, group = pres_hpa, color = pres_hpa)) + geom_line()

【问题讨论】:

    标签: r loops dataframe


    【解决方案1】:

    您只需将rbind 放入循环中,如下所示:

    library(dplyr)
    library(ggplot2)
    library(tidyverse)
    
    y = 1978
    N <- 10
    all.temp <- NULL
    
    for (i in 1:N) {
      yr = y +(as.numeric(i))
      yr = as.character(yr)
      p <- paste0("c:/Users/Hp/Documents/",yr,".csv")
    
      #read.csv
      dat <- read.csv(p,header = TRUE, stringsAsFactors = F)
      #filter
      dat_sub <- filter(dat, hght_m > 0)
      dat_sub <- filter(dat_sub, temp_c > 0)
      dat1_sub <- filter(dat_sub, pres_hpa == 1000)
      dat2_sub <- filter(dat_sub, pres_hpa == 925)
      dat3_sub <- filter(dat_sub, pres_hpa == 850)
      dat4_sub <- filter(dat_sub, pres_hpa == 700)
    
      all.temp <- rbind(all.temp, dat1_sub, dat2_sub, dat3_sub, dat4_sub)
    }
    
    ggplot(data = all.temp, aes(x= as.Date(date), y = temp_c, group = pres_hpa, color = pres_hpa)) + geom_line()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多