How to debug an invalid integer index in R

I'm trying to run R code : extract the maximum value in a vector under certain conditions , but I keep getting an 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 as follows:

 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 
+7
r
source share
2 answers

Sample code also works for me. But I found that I can reproduce a similar error if I try to do 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)"

+10
source share

Mistake

Sample code also works for me. However, as mentioned in schnee, you can create a similar error by replacing group_by (id) with group_by (dat $ id). Playable Code:

 dat1 <- data.frame(x=c('A','A','B','B'), y=c('A','B','C','D'), val = 1:4) dat2 <- data.frame(val = 1:4) dat_group <- data.frame(x=c('A','A','B','B')) # invalid subscript type 'integer' dat1 %>% group_by(dat1$x) %>% mutate(y = sum(unique(y) %in% c("A","B","C"))) # invalid subscript type 'list' dat2 %>% group_by(dat_group$x) %>% mutate(y = sum(unique(y) %in% c("A","B","C"))) 

While the former is usually just a typo (you can replace dat $ x with x), the latter may be a valid use case (although I would recommend joining to make it cleaner).

Decision

The dplyr package does not like the use of '$'. Try using '[' instead, for example:

 dat1[,'x'] 

Quoting a variable also works:

 dat1$'x' 

Full code:

 dat1 %>% group_by(dat1[,'x']) %>% mutate(y = sum(unique(y) %in% c("A","B","C"))) dat1 %>% group_by(dat1$'x') %>% mutate(y = sum(unique(y) %in% c("A","B","C"))) 

See also https://github.com/hadley/dplyr/issues/433 or https://github.com/hadley/dplyr/issues/1554

+6
source share

All Articles