使用下面的数据(包含在dput
中),我对三个人的重复纬度和经度位置有不同的看法,并希望使用dplyr
将其分布成较宽的格式。
数据如下:
> head(Dat)
IndIDII IndYear WintLat WintLong
1 BHS_265 BHS_265-2015 47.61025 -112.7210
2 BHS_265 BHS_265-2016 47.59884 -112.7089
3 BHS_770 BHS_770-2016 42.97379 -109.0400
4 BHS_770 BHS_770-2017 42.97129 -109.0367
5 BHS_770 BHS_770-2018 42.97244 -109.0509
6 BHS_377 BHS_377-2015 43.34744 -109.4821
This post提供了一个非常实用的解决方案。但是,我无法获得理想的结果。修改代码,我有以下内容:
Dat %>%
group_by(IndIDII) %>%
#Make YearNum (as intiger not calnader year) for each IndIDII
mutate(YearNum = row_number()) %>%
gather(Group, LatLong, c(WintLat, WintLong)) %>%
unite(GroupNew, YearNum, Group, sep = "-") %>%
spread(GroupNew, LatLong) %>%
as.data.frame()
这将产生几乎正确的结果,但是每个IndIDII
都有多个行,每个行都包含经度和纬度,为期一年。
IndIDII IndYear 1-WintLat 1-WintLong 2-WintLat 2-WintLong 3-WintLat 3-WintLong 4-WintLat 4-WintLong
1 BHS_265 BHS_265-2015 47.61025 -112.7210 NA NA NA NA NA NA
2 BHS_265 BHS_265-2016 NA NA 47.59884 -112.7089 NA NA NA NA
3 BHS_377 BHS_377-2015 43.34744 -109.4821 NA NA NA NA NA NA
4 BHS_377 BHS_377-2016 NA NA 43.35559 -109.4445 NA NA NA NA
5 BHS_377 BHS_377-2017 NA NA NA NA 43.35195 -109.4566 NA NA
6 BHS_377 BHS_377-2018 NA NA NA NA NA NA 43.34765 -109.4892
7 BHS_770 BHS_770-2016 42.97379 -109.0400 NA NA NA NA NA NA
8 BHS_770 BHS_770-2017 NA NA 42.97129 -109.0367 NA NA NA NA
9 BHS_770 BHS_770-2018 NA NA NA NA 42.97244 -109.0509 NA NA
我试图将IndIDII
的所有经度和纬度都放在一行(即宽格式)中,如下所示。当个人的年数少于最大年限时,将显示NA
值。我怀疑问题出在GroupNew
变量上,并尝试了其他选项,但无济于事...
Dat <- structure(list(IndIDII = c("BHS_265", "BHS_265", "BHS_770", "BHS_770",
"BHS_770", "BHS_377", "BHS_377", "BHS_377", "BHS_377"), IndYear = c("BHS_265-2015",
"BHS_265-2016", "BHS_770-2016", "BHS_770-2017", "BHS_770-2018",
"BHS_377-2015", "BHS_377-2016", "BHS_377-2017", "BHS_377-2018"
), WintLat = c(47.6102519805014, 47.5988417247191, 42.9737859090909,
42.9712914772727, 42.9724390816327, 43.3474354347826, 43.3555934579439,
43.3519543396226, 43.3476466990291), WintLong = c(-112.720994832869,
-112.708887595506, -109.039964727273, -109.036693522727, -109.050923061224,
-109.482114456522, -109.444522149533, -109.45659254717, -109.489241553398
)), class = "data.frame", row.names = c(NA, -9L))
答案 0 :(得分:1)
您快到了。 lat
和long
进入不同的行,因为它们的IndYear
不同。由于您只保留最后IndYear
中每个IndiDII
的{{1}}的第一个值,因此添加data.frame
将为您提供所需的结果。
IndYear = first(IndYear)