首页 文章

基于单独的Dataframe(R)的子集数据

提问于
浏览
0

我知道之前已经问过这个问题的变体,我尝试过(Select rows from a data frame based on values in a vector)和(subset a column in data frame based on another data frame/list)的解决方案,但我无法使这些解决方案有效 . 解决方案继续返回具有0个观察值的数据帧 .

我的第一个数据框看起来像这样:

> head(test3)
  long    lat     time   precip  GID_0   GID_1   HASC_1
168.75 -46.25 Jan_1979 5.534297   NZL  NZL.14_1  NZ.SO
171.25 -43.75 Jan_1979 4.191629   NZL  NZL.3_1   NZ.CA
146.25 -41.25 Jan_1979 3.139199   AUS  AUS.9_1   AU.TS
173.75 -41.25 Jan_1979 1.770889   NZL  NZL.8_1   NZ.MA
176.25 -38.75 Jan_1979 2.257812   NZL  NZL.17_1  NZ.WK
141.25 -36.25 Jan_1979 1.985313   AUS  AUS.10_1  AU.VI

我有一个单独的数据框,其中包含一个ID值如下所示的单个列:

> head(africa_iso)
ISO
DZA
AGO
SHN
BEN
BWA
BFA

我想过滤第一个数据帧,以便只保留与GID_0和ISO匹配的观察结果(从概念上讲,第一个数据集包括所有国家的观察结果,我想将其过滤为仅包含非洲国家观测数据的数据集) . 我目前在第一个数据帧中有725,517个观测值,我希望在滤波后有大约200k个观测值 .

到目前为止,这些都是我的尝试,每次我留下一个有7列且没有观察的新数据框 .

Afr <- subset(test3, GID_0 %in% africa_iso$ISO) #attempt 1

Afr <- setDT(test3)[GID_0 %in% africa_iso$ISO] #attempt 2

Afr <- test3[test3$GID_0 %in% africa_iso$ISO,] #attempt 3

Afr <- filter(test3$GID_0 %in% africa_iso$ISO  ) #attempt 4

Afr <- setDT(test3)[GID_0 %chin% africa_iso$ISO] #attempt 5

Afr <- test3[match(test3$GID_0, africa_iso$ISO),] #attempt 6

Afr <-test3[is.element(test3$GID_0, africa_iso$ISO),] #attempt 7

我相信这对其他人来说是一个微不足道的问题,但我会感激任何帮助 . 谢谢 .

编辑:

> str(test3)
Classes ‘data.table’ and 'data.frame':  725517 obs. of  7 variables:
 $ long  : num  169 171 146 174 176 ...
 $ lat   : num  -46.2 -43.8 -41.2 -41.2 -38.8 ...
 $ time  : Factor w/ 477 levels "Jan_1979","Feb_1979",..: 1 1 1 1 1 1 1 1 1        
 $ precip: num  5.53 4.19 3.14 1.77 2.26 ...
 $ ISO   :'data.frame': 725517 obs. of  1 variable:
..$ : chr  "NZL" "NZL" "AUS" "NZL" ...
 $ ISOP  :'data.frame': 725517 obs. of  1 variable:
..$ : chr  "NZL.14_1" "NZL.3_1" "AUS.9_1" "NZL.8_1" ...
 $ HASC  :'data.frame': 725517 obs. of  1 variable:
..$ : chr  "NZ.SO" "NZ.CA" "AU.TS" "NZ.MA" ...
- attr(*, ".internal.selfref")=<externalptr>

> str(africa_iso)
'data.frame':   62 obs. of  1 variable:
 $ ISO: Factor w/ 57 levels "AGO","BDI","BEN",..: 14 1 43 3 5 4 2 8 12 6 ...

1 回答

  • 1

    test3 中的几个列不正确 character :它们嵌入了 data.frame ,这使您的查找变得复杂 . 如果您没有故意这样做,可以通过以下方式纠正:

    isdf <- sapply(test3, is.data.frame)
    test3[isdf] <- lapply(test3[isdf], `[[`, 1)
    subset(test3, GID_0 %in% africa_iso$ISO)
    #     long    lat     time   precip GID_0    GID_1 HASC_1
    # 1 168.75 -46.25 Jan_1979 5.534297   NZL NZL.14_1  NZ.SO
    # 2 171.25 -43.75 Jan_1979 4.191629   NZL  NZL.3_1  NZ.CA
    # 4 173.75 -41.25 Jan_1979 1.770889   NZL  NZL.8_1  NZ.MA
    # 5 176.25 -38.75 Jan_1979 2.257812   NZL NZL.17_1  NZ.WK
    

    我之前更改了你的 africa_iso 以包含 NZL 以便匹配:

    > dput(africa_iso)
    structure(list(ISO = structure(c(5L, 1L, 6L, 2L, 4L, 3L), .Label = c("NZL", 
    "BEN", "BFA", "BWA", "DZA", "SHN"), class = "factor")), row.names = c(NA, 
    -6L), class = "data.frame")
    

相关问题