Replacing ^ and | sybmbols in a matrix

前端 未结 1 465
逝去的感伤
逝去的感伤 2020-12-22 12:53

I have the following table:

column1  column2
1        aaa^bbb
2        aaa^bbb|ccc^ffffd

I would like to have a output file as follows:

相关标签:
1条回答
  • 2020-12-22 12:59

    The easiest way to do what you are after, is just use strsplit. For example,

    > x = c("aaa^bbb", "aaa^bbb|ccc^ffffd")
    > ## Split the vector on ^ OR |.
    > ## Since ^ and | are special characters
    > ## we need to escape them: \\^ and \\|
    > ## Split by column.
    > new_x = unlist(strsplit(x, "\\|"))
    > ## Split by row
    > new_x = unlist(strsplit(new_x, "\\^"))
    > new_x
     [1] "aaa" "bbb" "aaa" "bbb" "ccc" "ffffd"
    
    > ## Change the vector back into a matrix
    > dim(new_x) = c(2,3)
    > ## Transpose to get correct shape
    > t(new_x)
         [,1]  [,2] 
    [1,] "aaa" "bbb"
    [2,] "aaa" "bbb"
    [3,] "ccc" "ffffd"
    

    You could probably combine the splitting step, but I don't have enough knowledge to your data format to be confident that it will always work.

    0 讨论(0)
提交回复
热议问题