问题 R使用“dplyr”编程来选择行并返回找到的行的索引


设置/问题:

使用dplyr - 我无法确定返回已过滤行的行索引的最佳方式,而不是返回已过滤行的内容。

问题:

我可以使用dplyr :: filter()从数据帧中提取行...问题是想要提取已过滤行的索引值并将其添加到符合搜索条件的索引条目列表中。

题:

是否有一种简单的方法可以使用dplyr根据特定条件搜索数据帧并返回找到的每一行的数字索引?下面的代码使用r :: which()将索引行提取到列表中......

    requiredPackages <- c("dplyr")

    ipak <- function(pkg){
            new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
            if (length(new.pkg))
                    install.packages(new.pkg, dependencies = TRUE)
            sapply(pkg, require, character.only = TRUE)
    }

    ipak(requiredPackages)

    if (!file.exists("./week3/data")) {
            dir.create("./week3/data")
    }

    # CSV Download
    if (!file.exists("./week3/data/americancommunitySurvey.csv")) {
            fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv?accessType=DOWNLOAD"
            download.file(fileUrl, destfile = "./week3/data/americancommunitySurvey.csv", method = "curl")
    }

    housingData <- tbl_df(read.csv("./week3/data/americancommunitySurvey.csv"
                                   , stringsAsFactors = TRUE))

 Now we have to extract the relevant data
#
# Create a logical vector that identifies the households on greater than 10
# acres who sold more than $10,000 worth of agriculture products. Assign that
# logical vector to the variable agricultureLogical. Apply the which() function
# like this to identify the rows of the data frame where the logical vector is
# TRUE. which(agricultureLogical) What are the first 3 values that result?
#
# ACR 1
# Lot size
# b .N/A (GQ/not a one-family house or mobile home)
# 1 .House on less than one acre
# 2 .House on one to less than ten acres
# 3 .House on ten or more acres                 ACR == 3
#
# AGS 1
# Sales of Agriculture Products
# b .N/A (less than 1 acre/GQ/vacant/
#                 .2 or more units in structure)
# 1 .None
# 2 .$ 1 - $ 999
# 3 .$ 1000 - $ 2499
# 4 .$ 2500 - $ 4999
# 5 .$ 5000 - $ 9999
# 6 .$10000+                                    AGS == 6
#
# Thus, we need to select only the results that have a ACR == 3 AND a AGS == 6
#
agricultureLogical <- which(housingData$ACR == 3 & housingData$AGS == 6)
agricultureLogical
# Now we can display the first three values of the resulting list
head(agricultureLogical[1:3])

上面的代码给了我想要的结果,但我想了解如何使用dplyr执行此操作。这是烦我的...我可以使用dplyr :: filter()如下提取行行 - 如何提取每行的索引?

agricultureLogical <- filter(housingData, ACR == 3 & housingData$AGS == 6)

R设置

版                _
平台x86_64-apple-darwin13.4.0
拱x86_64
os darwin13.4.0
system x86_64,darwin13.4.0
状态
专业3
小1.2
2014年
第10个月
第31天
svn rev 66913
语言R.
version.string R版本3.1.2(2014-10-31) 绰号南瓜头盔

dplyr版本0.3.0.2

设置Mac OS X.

型号名称:MacBook Pro   型号标识符:MacBookPro10,1   处理器名称:Intel Core i7   处理器速度:2.7 GHz   处理器数量:1   核心总数:4   L2缓存(每个核心):256 KB   L3缓存:8 MB   内存:16 GB


1952
2018-01-17 22:06


起源

我不确定是否有专门用于此的dplyr函数,但您可能使用的逻辑子集 1:n() - Rich Scriven
理查德 - 感谢您的帖子 - 您能提供更多信息吗? - Technophobe01
也许是这样的 do(mtcars, data.frame(x = which(.$cyl == 4))) 作为一个例子 mtcars 数据集并查找哪些行包含等于4的柱面。您可以添加 %>% .$x 在调用后得到一个向量而不是一个 data.frame 如果你选择 - Rich Scriven
如果你有这么简单的矢量化解决方案,为什么要使用 dplyr? - David Arenburg
David Arenburg - 我不清楚如何使用dplyr返回数据框中行的索引。我想知道该怎么做。我理解如何用R :: which()实现这一点基本上,我使用dplyr对一组标准搜索数据帧而不是返回我想要返回行的索引的行数据。我无法看到如何用dplyr这样做,因此问题。我知道如何根据代码使用它。 - Technophobe01


答案:


如果您使用的是dplyr> = 0.4,则可以执行以下操作

housingData %>%
  add_rownames() %>%
  filter(ACR == 3 & AGS == 6) %>%
  `[[`("rowname") %>%
  as.numeric() -> agricultureLogical

虽然为什么你会认为这是一个改进

agricultureLogical <- which(housingData$ACR == 3 & housingData$AGS == 6)

逃避我


9
2018-01-18 02:03



Ista,我不认为它更优越我只是想确定如何更优化地使用dplyr包。即,如何返回索引偏移号而不是行数据。 - Technophobe01
dplyr是首选,尤其是对于大型数据集,因为它经过优化可以更快地运行 - Servet
@Servet通常声称一种方法比基准测试更快。小心提供一个? - Ista
一个起点可能是 datascience.la/dplyr-and-a-very-basic-benchmark - Servet
@Servet我不知道那篇博文与这个问题有什么关系。对于某些事情,dplyr可能更快,但这个问题是提取符合某些标准的行号。 - Ista


提出的解决方案

这是我想要做的一个例子......这是一种解决方案,但我不喜欢它。感谢Richard Scriven指向1:n()的指针...

手动将索引列添加到数据框中...

我还没有想出如何为每个符合特定标准的行返回单个索引号...

所以我使用了一个索引列到示例数据框 dplyr:突变()。然后我用 dplyr ::滤波器() 在数据框架上,根据所需标准应用过滤器。这给我留下了我想要玩的行列表...包括原始数据框的索引......我现在使用 dplyr ::选择() 仅提取符合条件的每一行的原始数据框条目的索引列...

h1 <- housingData
# Add an index column to the dataframe h1...
h1 <- mutate(h1, IDX = 1:n())
# Filter the h1 dataframe using the criteria defined...
h1 <- filter(h1, ACR == 3 & housingData$AGS == 6)
# Extract the index 
h1 <- select(h1, IDX)
# Convert to an integer list...
agricultureLogical <- as.integer(as.character(h1$IDX))
head(agricultureLogical[1:3])

上面对我来说是重复的努力,因为索引隐含在原始数据框中。因此我的感觉是必须有一种方法来返回过滤器标识的项目的索引集...答案赞赏:-)


6
2018-01-18 00:52