【问题标题】:Subset dataframe based on several conditions in R基于R中几个条件的子集数据框
【发布时间】:2019-06-01 00:48:20
【问题描述】:

我正在尝试在多种条件下对大数据框(北半球的旋风轨迹)进行子集化:数据如下

centro <- read.table("https://forms.naturwissenschaften.ch/imilast/_ERAinterim_1.5_1979_MTEX/ERAinterim_1.5_NH_M02_19790101_20121231_MTEX.txt?_ga=2.18919096.1825595846.1546710263-1112023567.1546710263", sep="", fill = T, nrows = 500,
                 header = F, skip = 2) # read here only the first 500 rows

centro <- na.omit(centro)

colnames(centro) <- c("Code","CycloneNo","StepNo","DateI10","Year","Month","Day","Time","LongE","LatN","Intensity1","Intensity2","Intensity3")

当列 StepNo == 1 时,我只想对在空间框(如 -4 和 40 E 经度和 32-45 N lat)中形成的旋风(基于唯一列 CycloneNo)进行子集化。通常,这很容易做到:

centro_subs <- centro[centro$LongE>=-4 & centro$LongE <= 40 & centro$LatN>= 32 & centro$LatN <= 45,]

但是,我只想保留在此框内形成的旋风(当 StepNo ==1 时),但其余轨道也在此框外。

我试图通过这样做:

df_s <- centro[1,]
df_s[1,] <- NA # create an empty dataframe to be filled in the iteration


for (i in 1:length(unique(centro$CycloneNo))){
print(i)
a <- centro[centro$LongE[centro$StepNo==1]>= -4 & 
centro$LongE[centro$StepNo==1] <= 40 & 
centro$LatN[centro$StepNo==1]>= 32 & centro$LatN 
<=45[centro$StepNo==1],]
df_s <- rbind(a, df_s)
}

但是,这最终会生成一个填充有 NA 的空数据框。我知道这很难在这里描述。我觉得我有点接近了,但我现在也很疲惫,试图寻找新的方法。

【问题讨论】:

  • 我真的不明白你的问题。您的循环没有迭代任何内容(即不使用 i)。还有 ... centro$LatN
  • @Henrik - 是的,很抱歉。我把它减到了 500。
  • @Khaynes - 感谢您的提醒。我想我现在看到了问题所在。

标签: r loops dataframe subset


【解决方案1】:

我不认为你想要一个循环。我确信这不是最优雅的方法,但我认为它有效。

step1s <- subset(centro, StepNo == 1) # only take step 1 of all cyclones
keeps <- step1s$CycloneNo[step1s$LongE>=-4 & step1s$LongE <= 40 & step1s$LatN>= 32 & step1s$LatN <= 45] # find cyclone numbers for cyclones meeting the condition
centro_sub <- centro[centro$CycloneNo %in% keeps, ] # keep all steps of cyclones meeting the conditions

【讨论】:

    【解决方案2】:

    约瑟夫提供了一个很好的答案。或者,可以在 data.table 中使用它,这可能会以一些速度为代价提供更多的可读性。

    centro <- data.table(centro)
    centro[CycloneNo %in% CycloneNo[StepNo == 1 & 
                                      LongE %between% c(-4,40) & 
                                      LatN %between% c(32,45)]]
    

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2016-03-19
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2011-12-21
      • 2018-04-23
      相关资源
      最近更新 更多