我正在尝试执行一个看似简单的任务,即不使用单列。我搜索了stackoverflow,看来我应该使用tidyr::unnest()
函数。只有当我应用此功能时,它才将矢量列表的第一个价值保留在dataframe的单个单元格中。
我的数据示例:
library(tidyr)
df <- structure(list(properties.referentie = c("SDE1786673", "SDE1625351",
"SDE1636716"), geometry.coordinates = list(c(4.75813599901064,
52.272456042152), c(6.00720800022323, 51.9725940422743), c(4.51752499877652,
52.1393440422071))), .Names = c("properties.referentie", "geometry.coordinates"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))
我的代码不完整:
unnest(df, geometry.coordinates)
# A tibble: 6 x 2
properties.referentie geometry.coordinates
<chr> <dbl>
1 SDE1786673 4.76
2 SDE1786673 52.3
3 SDE1625351 6.01
4 SDE1625351 52.0
5 SDE1636716 4.52
6 SDE1636716 52.1
我实际上想从几何形状中创建两个列。
第一行和第二列包含以下值:c(4.75813599901064, 52.272456042152)
,因此我想要一个带有4.75813599901064
的列,而另一个列则在该向量52.272456042152
中具有另一个值。是LAT和LON数据。
tidyverse
的另一个解决方案:
df %>%
unnest() %>%
group_by(properties.referentie) %>%
summarise(lat = first(geometry.coordinates), lon = last(geometry.coordinates))
# A tibble: 3 x 3
properties.referentie lat lon
<chr> <dbl> <dbl>
1 SDE1625351 6.01 52.0
2 SDE1636716 4.52 52.1
3 SDE1786673 4.76 52.3
unnest
之后,我们可以 spread
to'wide'格式
library(tidyverse)
df %>%
unnest(geometry.coordinates) %>%
group_by(properties.referentie) %>%
mutate(rn = paste0("geometry.coordinates", row_number())) %>%
spread(rn, geometry.coordinates)
# A tibble: 3 x 3
# Groups: properties.referentie [3]
# properties.referentie geometry.coordinates1 geometry.coordinates2
# <chr> <dbl> <dbl>
# 1 SDE1625351 6.01 52.0
# 2 SDE1636716 4.52 52.1
# 3 SDE1786673 4.76 52.3
,或者可以通过将其转换为list
unnest
之前完成 df %>%
mutate(geometry.coordinates = map(geometry.coordinates,
~as.list(.) %>%
set_names(paste0("geometry.coordinates", seq_along(.x))) %>%
as_tibble)) %>%
unnest
# A tibble: 3 x 3
# properties.referentie geometry.coordinates1 geometry.coordinates2
# <chr> <dbl> <dbl>
# 1 SDE1786673 4.76 52.3
# 2 SDE1625351 6.01 52.0
# 3 SDE1636716 4.52 52.1
注意:两个解决方案都适用于每个list
元素中的任何length
iiuc,您可以使用sapply
使用unlist
来从列表类型列创建列。
cbind(df$properties.referentie,data.frame(t(sapply(df$geometry.coordinates,unlist))))
df$properties.referentie X1 X2
1 SDE1786673 4.758136 52.27246
2 SDE1625351 6.007208 51.97259
3 SDE1636716 4.517525 52.13934