【问题标题】:R: divide a factor or string variable into two new variablesR:将一个因子或字符串变量分成两个新变量
【发布时间】:2019-10-24 14:15:57
【问题描述】:

大家好,我有一个数据框,其中包含一个名为 the_geom_OBJECTID 的列,它表示一个阶乘变量。

                               the_geom_OBJECTID 
                                           <fct>
1   POINT  (-73.8472005205491 40.89470517661004) 
2  POINT  (-73.82993910812405 40.87429419303015) 
3  POINT  (-73.82780644716419 40.88755567735082) 
4 POINT  (-73.90564259591689 40.895437426903875) 
5  POINT  (-73.91258546108577 40.89083449389134) 
6  POINT  (-73.90281798724611 40.88168737120525)

我想将此数据框的列替换为两列,一列用于经度,另一列用于纬度

预期输出:

           longitude            latitude
               <dbl>               <dbl>
1  -73.8472005205491   40.89470517661004
2 -73.82993910812405   40.87429419303015
3 -73.82780644716419   40.88755567735082
4 -73.90564259591689  40.895437426903875
5 -73.91258546108577   40.89083449389134
6 -73.90281798724611   40.88168737120525

将变量转换为字符串格式然后创建两个新列会更好吗?

【问题讨论】:

    标签: r variables


    【解决方案1】:

    最简单的方法是使用 sf::st_coordinates():

    sf::st_coordinates(the_geom_OBJECTID)
    

    更新:

    首先将您的数据框转换为 sf 对象。

    library(sf)
    
    df <- data.frame(the_geom_OBJECTID = c("POINT  (-73.8472005205491 40.89470517661004)", 
                                           "POINT  (-73.82993910812405 40.87429419303015)", 
                                           "POINT  (-73.82780644716419 40.88755567735082)", 
                                           "POINT  (-73.90564259591689 40.895437426903875)", 
                                           "POINT  (-73.91258546108577 40.89083449389134)", 
                                           "POINT  (-73.90281798724611 40.88168737120525)"))
    
    df_sf <- st_sf(st_as_sfc(df$the_geom_OBJECTID))
    

    然后:

    sf::st_coordinates(df_sf)
    

    【讨论】:

    • 我收到了这个sf::st_coordinates(the_geom_OBJECTID) Error in UseMethod("st_coordinates") : no applicable method for 'st_coordinates' applied to an object of class "factor"
    • 您应该包含dput 版本的数据,以便我们测试您的问题的答案。
    猜你喜欢
    • 2019-05-01
    • 2022-12-16
    • 2021-12-03
    • 1970-01-01
    • 2021-08-23
    • 2020-12-20
    • 2018-03-03
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多