首页 文章

R-将具有字符串值(包含2个数字并用逗号分隔)的数据帧列拆分为2列

提问于
浏览
1

我有一个数据框 ddata ,其中变量 Location 具有以逗号分隔的字符串格式的纬度和经度 . 所以当我在控制台中键入 ddata$Location 时,我看到了这个:

"33.9829, -118.3338"
"34.0454, -118.3157"
"33.942,  -118.2717"
"33.9572, -118.2717"

如何用逗号(分隔符)分隔此列,并将其变为2列,名为: LongitudeLatitude ?我已经尝试过拆分功能但无法使其工作 .

3 回答

  • 2

    library(tidyr) separate(ddata, ddata$Location, c("Longitude", "Latitude"), ",")

  • 3

    由于它由 , 分隔,最简单的选项是 read.csv (假设'Location'的类是 character 而不是 factor . 如果是因子,则将其转换为 character (使用 as.character(ddata$Location)

    out <- read.csv(text = ddata$Location, header = FALSE,
          col.names = c("Latitude", "Longitude"))
    

    现在,我们 cbind 它与原始数据

    ddataNew <- cbind(dddata, out)
    
  • 1

    您可以在 stringr 包中使用 str_split_fixed 函数,如下所示:

    library(stringr)
    ddata[,c("Longitude", "Latitude")] <- str_split_fixed(ddata$Location, ", ", 2)
    

    它会给你:

    #             Location  Longitude   Latitude
    # 1 33.9829, -118.3338    33.9829  -118.3338
    # 2 34.0454, -118.3157    34.0454  -118.3157
    # 3  33.942, -118.2717     33.942  -118.2717
    # 4 33.9572, -118.2717    33.9572  -118.2717
    

    然后,如果要删除 Location 列,可以使用:

    ddata$Location <- NULL
    

    要得到这个:

    #   Longitude   Latitude
    # 1   33.9829  -118.3338
    # 2   34.0454  -118.3157
    # 3    33.942  -118.2717
    # 4   33.9572  -118.2717
    

    希望能帮助到你 .

相关问题