如何重新格式化数据并进行映射? [英] How can I reformat the data and map it?
本文介绍了如何重新格式化数据并进行映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有数据,其中列名是城市,行名是经度和纬度.
Let's say I have data where the column name is the city and row name is the longitude and latitude.
Columbus Nashville Austin Washington D.C. London Manchester
lon -82.99879 -86.7816 -97.74306 -77.03687 -0.1277583 -2.242631
lat 39.96118 36.16266 30.26715 38.90719 51.50735 53.48076
有没有办法我可以重新设置格式,所以我有:
Is there a way that I can reformat this so I have:
City lon lat
Columbus 82.99879 39.96118
Nashville -86.7816 36.16266
生成数据的代码:
df <- structure(
list(
Columbus = structure(
list(lon = -82.9987942, lat = 39.9611755), .Names = c("lon", "lat")),
Nashville = structure(
list(lon = -86.7816016, lat = 36.1626638), .Names = c("lon", "lat")),
Austin = structure(
list(lon = -97.7430608, lat = 30.267153), .Names = c("lon", "lat")),
`Washington D.C.` = structure(
list(lon = -77.0368707, lat = 38.9071923), .Names = c("lon", "lat")),
London = structure(
list(lon = -0.1277583, lat = 51.5073509), .Names = c("lon", "lat")),
Manchester = structure(
list(lon = -2.2426305, lat = 53.4807593), .Names = c("lon", "lat"))),
.Names = c("Columbus", "Nashville", "Austin", "Washington D.C.",
"London", "Manchester"),
row.names = c("lon", "lat"), class = "data.frame")
我的最终目标是映射它,但是使用原始格式,它不起作用.
My final goal is to map it but with the original format, it does not work.
我尝试过:
tibble::rownames_to_column(as.data.frame(df))
data.table::setDT(as.data.frame(df))[]
然后进行映射:
leaflet(data = df) %>%
addProviderTiles("Thunderforest.OpenCycleMap") %>%
addMarkers(~lon, ~lat)
推荐答案
只需转置数据:
library(dplyr) #for mutate, if you so choose to use it
df.new <- t(df)
df.new <- as.data.frame(df.new) #if you want a dataframe instead
df.new <- df.new %>% mutate(City=rownames(.))
输出:
lon lat City
1 -82.99879 39.96118 Columbus
2 -86.7816 36.16266 Nashville
3 -97.74306 30.26715 Austin
4 -77.03687 38.90719 Washington D.C.
5 -0.1277583 51.50735 London
6 -2.242631 53.48076 Manchester
我喜欢管道,因此您可以只写一行:
I love pipes, so you could just write one line:
df %>% t() %>% as.data.frame() %>% mutate(City=rownames(.))
这篇关于如何重新格式化数据并进行映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文