【发布时间】:2015-08-25 05:01:52
【问题描述】:
我正在做数据清理。我在 Dplyr 中经常使用 mutate,因为它会逐步生成新列,我可以很容易地看到它是如何进行的。
这是我遇到此错误的两个示例
Error: incompatible size (%d), expecting %d (the group size) or 1
示例 1:从邮政编码获取城镇名称。数据就是这样的:
Zip
1 02345
2 02201
我注意到当数据中有 NA 时,它不起作用。
没有 NA 它可以工作:
library(dplyr)
library(zipcode)
data(zipcode)
test = data.frame(Zip=c('02345','02201'),stringsAsFactors=FALSE)
test %>%
rowwise() %>%
mutate( Town1 = zipcode[zipcode$zip==na.omit(Zip),'city'] )
导致
Source: local data frame [2 x 2]
Groups: <by row>
Zip Town1
1 02345 Manomet
2 02201 Boston
对于 NA,它不起作用:
library(dplyr)
library(zipcode)
data(zipcode)
test = data.frame(Zip=c('02345','02201',NA),stringsAsFactors=FALSE)
test %>%
rowwise() %>%
mutate( Town1 = zipcode[zipcode$zip==na.omit(Zip),'city'] )
导致
Error: incompatible size (%d), expecting %d (the group size) or 1
示例 2。我想去掉以下数据中 Town 列中出现的冗余州名。
Town State
1 BOSTON MA MA
2 NORTH AMAMS MA
3 CHICAGO IL IL
这就是我的做法: (1) 将 Town 中的字符串拆分为单词,例如第 1 行的“波士顿”和“MA”。 (2) 查看这些词是否与该行的状态匹配 (3) 删除匹配词
library(dplyr)
test = data.frame(Town=c('BOSTON MA','NORTH AMAMS','CHICAGO IL'), State=c('MA','MA','IL'), stringsAsFactors=FALSE)
test %>%
mutate(Town.word = strsplit(Town, split=' ')) %>%
rowwise() %>% # rowwise ensures every calculation only consider currect row
mutate(is.state = match(State,Town.word ) ) %>%
mutate(Town1 = Town.word[-is.state])
这会导致:
Town State Town.word is.state Town1
1 BOSTON MA MA <chr[2]> 2 BOSTON
2 NORTH AMAMS MA <chr[2]> NA NA
3 CHICAGO IL IL <chr[2]> 2 CHICAGO
含义:例如,第 1 行显示 is.state==2,表示 Town 中的第二个单词是州名。摆脱这项工作后,Town1 是正确的城镇名称。
现在我想修复第 2 行中的 NA,但添加 na.omit 会导致错误:
test %>%
mutate(Town.word = strsplit(Town, split=' ')) %>%
rowwise() %>% # rowwise ensures every calculation only consider currect row
mutate(is.state = match(State,Town.word ) ) %>%
mutate(Town1 = Town.word[-na.omit(is.state)])
结果:
Error: incompatible size (%d), expecting %d (the group size) or 1
我检查了数据类型和大小:
test %>%
mutate(Town.word = strsplit(Town, split=' ')) %>%
rowwise() %>% # rowwise ensures every calculation only consider currect row
mutate(is.state = match(State,Town.word ) ) %>%
mutate(length(is.state) ) %>%
mutate(class(na.omit(is.state)))
结果:
Town State Town.word is.state length(is.state) class(na.omit(is.state))
1 BOSTON MA MA <chr[2]> 2 1 integer
2 NORTH AMAMS MA <chr[2]> NA 1 integer
3 CHICAGO IL IL <chr[2]> 2 1 integer
所以它是长度的 %d==1。有人可以在哪里出错吗?谢谢
【问题讨论】: