【问题标题】:Unnest list into two separate columns将列表取消嵌套到两个单独的列中
【发布时间】:2021-11-08 12:14:00
【问题描述】:

我想使用 tidyverse 语法(如 mutate 函数)将列表取消嵌套到两个单独的列中。

例如:

data %>% mutate_at("centroid", unnest_wider)

给我以下错误:

x 参数 col 缺失且没有默认值

我尝试使用

分配列名
.cols=c("X", "Y")

在代码中,但我仍然收到错误。

示例数据:

data <- structure(list(disasterno = c("2009-0631", "2009-0631", "2001-0146", 
"2009-0092", "2009-0092", "2009-0092"), centroid = structure(list(
    structure(c(19.4183172957388, 42.0209484621449), class = c("XY", 
    "POINT", "sfg")), structure(c(19.5143087402113, 41.9592941221655
    ), class = c("XY", "POINT", "sfg")), structure(c(15.6657576094231, 
    -17.093484362207), class = c("XY", "POINT", "sfg")), structure(c(15.7739867740437, 
    -16.5315326589011), class = c("XY", "POINT", "sfg")), structure(c(15.7739867740437, 
    -16.5315326589011), class = c("XY", "POINT", "sfg")), structure(c(15.7739867740437, 
    -16.5315326589011), class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT", 
"sfc"), precision = 0, bbox = structure(c(xmin = 15.6657576094231, 
ymin = -17.093484362207, xmax = 19.5143087402113, ymax = 42.0209484621449
), class = "bbox"), crs = structure(list(input = "EPSG:4326", 
    wkt = "GEOGCRS[\"WGS 84\",\n    DATUM[\"World Geodetic System 1984\",\n        ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n            LENGTHUNIT[\"metre\",1]]],\n    PRIMEM[\"Greenwich\",0,\n        ANGLEUNIT[\"degree\",0.0174532925199433]],\n    CS[ellipsoidal,2],\n        AXIS[\"geodetic latitude (Lat)\",north,\n            ORDER[1],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        AXIS[\"geodetic longitude (Lon)\",east,\n            ORDER[2],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n    USAGE[\n        SCOPE[\"Horizontal component of 3D system.\"],\n        AREA[\"World.\"],\n        BBOX[-90,-180,90,180]],\n    ID[\"EPSG\",4326]]"), class = "crs"), n_empty = 0L)), row.names = c(NA, 
6L), class = "data.frame")

【问题讨论】:

  • 请提供示例输入数据(您要使用的列表)。

标签: r tidyverse


【解决方案1】:
> data %>% tidyr::unnest_wider(centroid)
# A tibble: 6 × 3
  disasterno  ...1  ...2
  <chr>      <dbl> <dbl>
1 2009-0631   19.4  42.0
2 2009-0631   19.5  42.0
3 2001-0146   15.7 -17.1
4 2009-0092   15.8 -16.5
5 2009-0092   15.8 -16.5
6 2009-0092   15.8 -16.5

【讨论】:

    【解决方案2】:

    另一种解决方案,基于tidyr::separate

    library(tidyverse)
    
    data %>%
      separate(centroid, into = c("cent1", "cent2"), sep=", ") %>% 
      mutate(across(2:3, ~ parse_number(.)))
    
    #>   disasterno    cent1     cent2
    #> 1  2009-0631 19.41832  42.02095
    #> 2  2009-0631 19.51431  41.95929
    #> 3  2001-0146 15.66576 -17.09348
    #> 4  2009-0092 15.77399 -16.53153
    #> 5  2009-0092 15.77399 -16.53153
    #> 6  2009-0092 15.77399 -16.53153
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 2018-07-19
      • 1970-01-01
      • 2018-01-01
      • 2021-02-16
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多