Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to debug invalid subscript type 'integer' error in R

Tags:

r

I'm trying to run the code in R: extract maximum value in vector under certain conditions but I keep getting the error

Error in list(id.2 = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,  : 
  invalid subscript type 'integer'

The code is the following:

require(dplyr)
dat <- read.table(header = TRUE, text = "id    name    year    job    job2 cumu_job2
1   Jane    1980    Worker  0   0
1   Jane    1981    Manager 1   1
1   Jane    1982    Sales   0   0
1   Jane    1983    Sales   0   0
1   Jane    1984    Manager 1   1
1   Jane    1985    Manager 1   2
1   Jane    1986    Boss    0   0
2   Bob     1985    Worker  0   0
2   Bob     1986    Sales   0   0
2   Bob     1987    Manager 1   1
2   Bob     1988    Manager 1   2
2   Bob     1989    Boss    0   0
3   Jill    1989    Worker  0   0
3   Jill    1990    Boss    0   0")

dat %.%
  group_by(id) %.%
  mutate(
    all_jobs = sum(unique(job) %in% c("Sales","Manager","Boss")),
    cumu_max = max(cumu_job2)
  ) %.%
  filter(all_jobs == 3, job %in% c("Sales","Boss"))

Source: local data frame [5 x 8]
Groups: id

  id name year   job job2 cumu_job2 all_jobs cumu_max
1  1 Jane 1982 Sales    0         0        3        2
2  1 Jane 1983 Sales    0         0        3        2
3  1 Jane 1986  Boss    0         0        3        2
4  2  Bob 1986 Sales    0         0        3        2
5  2  Bob 1989  Boss    0         0        3        2
like image 604
song0089 Avatar asked Feb 06 '14 09:02

song0089


1 Answers

The sample code works for me, too. But I have found that I can repro a similar error if I attempt this:

dat %.%
 group_by(dat$id) %.%
 mutate(
     all_jobs = sum(unique(job) %in% c("Sales","Manager","Boss")),
     cumu_max = max(cumu_job2)
 ) %.%
 filter(all_jobs == 3, job %in% c("Sales","Boss"))

that is, if I type "group_by(dat$id)" instead of "group_by(id)"

like image 123
schnee Avatar answered Sep 23 '22 03:09

schnee