如何在R中调试无效的下标类型'整数'错误

时间:2014-02-06 09:07:53

标签: r

我正在尝试运行R: extract maximum value in vector under certain conditions中的代码,但我一直收到错误

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

代码如下:

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

2 个答案:

答案 0 :(得分:10)

示例代码也适用于我。但我发现如果我尝试这样做,我可以重现类似的错误:

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"))

也就是说,如果我输入“group_by(dat $ id)”而不是“group_by(id)”

答案 1 :(得分:6)

<强>错误

示例代码也适用于我。但是,正如schnee所提到的,您可以通过group_by(dat $ id)替换group_by(id)来创建类似的错误。可重现的代码:

dat1[,'x']

虽然第一个通常只是一个拼写错误(你可以用x替换dat $ x),但第二个可能是一个有效的用例(尽管我建议使用连接来使其更清晰)。

<强>解决方案

dplyr包不喜欢&#39; $&#39;的使用。请尝试使用&#39; [&#39;,例如:

dat1$'x'

引用变量也有效:

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")))

完整代码:

<script type="text/ng-template" id="template1.html">
    <div class="modal_content"> {{data[0]}}</div>
</script>

另请参阅http://goo.gl/2hdIrahttps://github.com/hadley/dplyr/issues/433