% pivot_longer(cols = -id) %>% separate(value, int-6ren">
gpt4 book ai didi

R::在r中将字符串从 "x,y"反转为 "y,x"

转载 作者:行者123 更新时间:2023-12-05 09:05:37 37 4
gpt4 key购买 nike

我有一张这样的 table

aa<-tribble(
~"a",~"b",~"c",~"d",
" 78.1445111, 9.9365072", "78.1444646, 9.9365044", " 78.1445111, 9.9365072", "78.1444646, 9.9365044",
"78.1444197, 9.9365166", "78.1443816, 9.9365422",
"78.142359, 9.9365748", "78.1421918, 9.9366057",
"78.1421918, 9.9366057", "78.1419488, 9.9367106",
"78.1444197, 9.9365166", "78.1443816, 9.9365422",
"78.142359, 9.9365748", "78.1421918, 9.9366057",
"78.1421918, 9.9366057", "78.1419488, 9.9367106",
)

这些是“纬度、经度”值。我想将它们转换成“long, lat”。例如,我想将“78.1445111, 9.9365072”转换为“9.9365072,78.1445111”。在 r 中是否可以对所有列进行自动化?

我期望在所有列中都有这样的输出:

   a<- tribble(
~"a",~"b",~"c",~"d",
"9.9365072,78.1445111", "9.9365044,78.1444646,", "9.9365072,78.1445111", "9.9365044,78.1444646,",
"9.9365166,78.1444197", "9.9365422,78.1443816",
"9.9365748,78.142359", "9.9366057,78.1421918",
"9.9366057,78.1421918", "9.9367106,78.1419488",
"9.9365166,78.1444197", "9.9365422,78.1443816",
"9.9365748,78.142359", "9.9366057,78.1421918",
"9.9366057,78.1421918", "9.9367106,78.1419488"
)

我尝试过但失败了:

bag_1<-list()
for(i in colnames(a)){
dummy <-str_split_fixed(a[[i]], ",", 2)

bag_1[[i]]<-dummy

dum<-do.call(rbind,bag_1)
}

最佳答案

这样可以吗?使用 dplyrtidyr 函数

library(tidyverse)

aa %>% mutate(id = row_number()) %>%
pivot_longer(cols = -id) %>%
separate(value, into = c("Lat", "Long"), sep = ", ") %>%
mutate(new = paste(Long, Lat, sep = ", ")) %>%
select(-Lat, -Long) %>%
pivot_wider(id_cols = id, names_from = name, values_from = new)

# A tibble: 4 x 5
id a b c d
<int> <chr> <chr> <chr> <chr>
1 1 9.9365072, 78.1445111 9.9365044, 78.1444646 9.9365072, 78.1445111 9.9365044, 78.1444646
2 2 9.9365166, 78.1444197 9.9365422, 78.1443816 9.9365748, 78.142359 9.9366057, 78.1421918
3 3 9.9366057, 78.1421918 9.9367106, 78.1419488 9.9365166, 78.1444197 9.9365422, 78.1443816
4 4 9.9365748, 78.142359 9.9366057, 78.1421918 9.9366057, 78.1421918 9.9367106, 78.1419488

aa 使用

aa <- tribble(
~"a",~"b",~"c",~"d",
"78.1445111, 9.9365072", "78.1444646, 9.9365044", "78.1445111, 9.9365072", "78.1444646, 9.9365044",
"78.1444197, 9.9365166", "78.1443816, 9.9365422",
"78.142359, 9.9365748", "78.1421918, 9.9366057",
"78.1421918, 9.9366057", "78.1419488, 9.9367106",
"78.1444197, 9.9365166", "78.1443816, 9.9365422",
"78.142359, 9.9365748", "78.1421918, 9.9366057",
"78.1421918, 9.9366057", "78.1419488, 9.9367106",
)

关于R::在r中将字符串从 "x,y"反转为 "y,x",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66948511/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com