用两个分隔符连接矩阵行

时间:2018-03-05 06:02:35

标签: r matrix apply paste sp

我的目标是将坐标对矩阵转换为单个字符串,并将坐标对粘贴在一起。例如,我有一个行字符串的坐标:

 mat <- routes@lines[[9]]@Lines[[1]]@coords
 mat
          [,1]    [,2]
[1,] -122.4491 37.7698
[2,] -122.4519 37.7694
[3,] -122.4491 37.7698

我想转换成这个:

"-122.4491,37.7698;-122.4519,37.7694;-122.4491,37.7698"

其中单个对的lat和lon用逗号分隔,并且用分号分隔对。

apply(format(mat), 1, paste, sep=";", collapse = "") 

不会产生所需的输出。如何在R中做到这一点?

以下是示例数据:

dput(mat)
structure(c(-122.4491, -122.4519, -122.4491, 37.7698, 37.7694, 
37.7698), .Dim = c(3L, 2L))

3 个答案:

答案 0 :(得分:3)

mat <- structure(c(-122.4491, -122.4519, -122.4491, 37.7698, 37.7694, 37.7698), .Dim = c(3L, 2L))

这是一个矩阵,坐标分为两列。您只需使用一个调用即可粘贴。

paste(mat[,1], mat[,2], sep = ",", collapse = ";")
# [1] "-122.4491,37.7698;-122.4519,37.7694;-122.4491,37.7698"

这里sep设置lat和long坐标(同一行中的单元格)之间的分隔符,collapse设置坐标对之间的分隔符(不同行之间的分隔符)。

答案 1 :(得分:2)

mat <- structure(c(-122.4491, -122.4519, -122.4491, 37.7698, 37.7694, 37.7698), .Dim = c(3L, 2L))

你很亲密。您使用apply是合适的,但由于您在第一行操作,您需要先担心一个分隔:

apply(mat, 1, paste, collapse=",")
# [1] "-122.4491,37.7698" "-122.4519,37.7694" "-122.4491,37.7698"

...然后将所有这些内容与一个外部paste合并:

paste(apply(mat, 1, paste, collapse=","), collapse=";")
# [1] "-122.4491,37.7698;-122.4519,37.7694;-122.4491,37.7698"

答案 2 :(得分:1)

另一种选择是转换为data.frame,然后使用do.call

do.call(paste, c(as.data.frame(mat), collapse=";", sep=","))
#[1] "-122.4491,37.7698;-122.4519,37.7694;-122.4491,37.7698"