【发布时间】:2015-03-16 07:00:55
【问题描述】:
设置/问题:
使用 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
操作系统 darwin13.4.0
系统 x86_64,darwin13.4.0
状态
专业 3
次要 1.2
2014 年
第 10 个月
第 31 天
svn 版本 66913
语言 R
version.string R 版本 3.1.2 (2014-10-31)
昵称南瓜头盔
dplyr 版本 0.3.0.2
设置 Mac OS X
型号名称:MacBook Pro 型号标识符:MacBookPro10,1 处理器名称:英特尔酷睿 i7 处理器速度:2.7 GHz 处理器数量:1 核心总数:4 L2 缓存(每核):256 KB 三级缓存:8 MB 内存:16 GB
【问题讨论】:
-
我不确定是否有专门用于此的 dplyr 函数,但您可能可以使用
1:n()的逻辑子集 -
Richard - 感谢您的帖子 - 您能提供更多信息吗?
-
可能类似于
do(mtcars, data.frame(x = which(.$cyl == 4)))以mtcars数据集为例并查找哪些行包含等于4 的柱面。您可以在调用后添加%>% .$x以获取向量而不是data.frame如果您选择 -
如果你有这么简单的矢量化解决方案,为什么要使用
dplyr? -
David Arenburg - 我不清楚如何使用 dplyr 返回数据框中的行索引。我想知道该怎么做。我了解如何使用 R::which() 执行此操作 本质上,我正在使用 dplyr 针对一组标准搜索数据框,而不是返回我想要返回行索引的行数据。我看不出如何用 dplyr 做到这一点,因此这个问题。我知道如何根据代码使用 which 来做到这一点。