Reputation: 531
I'm trying to replace all the subset
calls in my script by using dplyr
:
Here is a problem I encounter while trying to subset data.
options(stringsAsFactors=F, width=175)
library(dplyr)
d <- data.frame(
col1 = c('a', 'b', 'c', 'd'),
col2 = c(1, 2, 3, 4))
f <- data.frame(
col1 = c('a', 'd', 'c'),
col2 = c('a', 'd', 'c'),
col3 = c('a', 'd', 'c'),
flag = c('blue', 'blue', 'red'))
filter(d, col1 %in% filter(f, flag == 'blue')$col1)
filter(d, col1 %in% filter(f, flag == 'blue')$col2)
filter(d, col1 %in% filter(f, flag == 'blue')$col3)
Output:
> filter(d, col1 %in% filter(f, flag == 'blue')$col1)
[1] col1 col2
<0 rows> (or 0-length row.names)
> filter(d, col1 %in% filter(f, flag == 'blue')$col2)
Error: invalid subscript type 'double'
> filter(d, col1 %in% filter(f, flag == 'blue')$col3)
col1 col2
1 a 1
2 d 4
Looks like it depends on the name of the column. Is this expected ? What am I doing wrong ?
Thank you !
Session :
R version 3.2.0 (2015-04-16)
Platform: x86_64-unknown-linux-gnu (64-bit)
Running under: CentOS release 6.6 (Final)
locale:
[1] LC_CTYPE=en_CA.UTF-8 LC_NUMERIC=C LC_TIME=en_CA.UTF-8 LC_COLLATE=en_CA.UTF-8 LC_MONETARY=en_CA.UTF-8 LC_MESSAGES=en_CA.UTF-8
[7] LC_PAPER=en_CA.UTF-8 LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.4.3
loaded via a namespace (and not attached):
[1] lazyeval_0.1.10 magrittr_1.5 R6_2.1.1 assertthat_0.1 parallel_3.2.0 tools_3.2.0 DBI_0.3.1 Rcpp_0.12.0
Upvotes: 1
Views: 421
Reputation: 226087
Nesting functions with non-standard evaluation (like filter
) seems like asking for trouble; it's very tricky for dplyr
that you want to evaluate the expression col1
in two different environments (f
and d
). Any of the following will work:
filter(d, col1 %in% filter(f,flag=="blue")[["col1"]])
or
filter(d,col1 %in% f$col1[f$flag=="blue"])
or
vals <- filter(f,flag=="blue")$col1
filter(d,col1 %in% vals)
Upvotes: 1