0

Using data is a question just asked here, I wanted to spread the data using tidyr using extract().

df<-read.table(header=T,text=
                "id m1      m2     m3
 P001.st   60.00   2.0     1
 P003.nd   14.30   2.077   1
 P003.rt   29.60   2.077   1
 P006.st   10.30   2.077   1
 P006.nd   79.30   2.077   1
 P008.nd    9.16   2.077   1")

df %>% 
  extract(id, c("id2", "var"), c("(P00.)\\.(..)"))

Which was based off an answer from hadley here.

But I get the error:

Error in drop && length(x) == 1L : invalid 'x' type in 'x && y'

I don't normally use regular expressions, but would like to start to, so if someone could help me understand where I'm failing, it'd be much appreciated.

thanks!

Community
  • 1
  • 1
Andrew Taylor
  • 3,438
  • 1
  • 26
  • 47
  • I cannot replicate your error. I use dplyr 0.4.1.9000...It works fine. – Miha Trošt Mar 10 '15 at 12:41
  • Yes, getting rid of the c() made it work. Can you explain why @hadley's response in my linked stackoverflow response includes the c()? – Andrew Taylor Mar 10 '15 at 12:44
  • Wouldn't this be easier with `separate`? e.g. `df %>% separate(id, c("id2", "var"), "\\.")` – talat Mar 10 '15 at 12:46
  • For this particular example, sure. But using extract() with regular expressions can give greater flexibility down the road. – Andrew Taylor Mar 10 '15 at 12:52
  • @MihaTrošt, `extract` is from tidyr, not dplyr. @Andrew: I can't reproduce the error with tidyr 0.2.0. What version are you running? – talat Mar 10 '15 at 12:58
  • I'm using `tidyr_0.2.0`. The issue seems to be that I included the `c()` outside of the regular expression. Did you exclude this, or is it working with the `c()` included? – Andrew Taylor Mar 10 '15 at 13:00
  • I used `extract(df, id, c("id2", "var"), c("(P00.)\\.(..)"))` and `extract(df, id, c("id2", "var"), "(P00.)\\.(..)")` (and the separate version above) and they all produce the same output without error message. Maybe restart R with a new session? – talat Mar 10 '15 at 13:01
  • @docendodiscimus Just kidding. Now it's working just fine with the c(). I guess I didn't have `tidyr` loaded and it was using a different `extract` or something...I have no idea – Andrew Taylor Mar 10 '15 at 13:02
  • 1
    Ok that's good. I'm voting to close the question then as "a problem that can no longer be reproduced or a simple typographical error". – talat Mar 10 '15 at 13:04

1 Answers1

3

Probably your script is loading also magrittr after loading tidyr but you forgot to mention.

So you are actually referencing magrittr::extract instead of tidyr::extract.

You can either

  1. Load magrittr before loading tidyr; or
  2. Reference tidyr::extract explicitly.

Both must work.

Marcelo Ventura
  • 581
  • 7
  • 19