如何将带有几行代码的字符矩阵转换为不同的矩阵?

时间:2016-08-05 22:29:11

标签: r

我有以下matric(我不坚持矩阵类型 - 它也可能是data.frame,...):

df <- structure(c("Jan-01", "Dec-31", "00-00", "24-00", "Jan-01", "Jun-30", 
"12-00", "18-00", "Jul-06", "Dec-31", "09-00", "19-00", "Jul-06", 
"Dec-31", "09-00", "19-00"), .Dim = c(4L, 4L), .Dimnames = list(
    NULL, c("V1", "V2", "V3", "V4")))

#      V1       V2       V3       V4      
# [1,] "Jan-01" "Jan-01" "Jul-06" "Jul-06"
# [2,] "Dec-31" "Jun-30" "Dec-31" "Dec-31"
# [3,] "00-00"  "12-00"  "09-00"  "09-00" 
# [4,] "24-00"  "18-00"  "19-00"  "19-00" 

如何让它看起来像

       V1   V2    V3    V4
[1,] "Jan" "Jan" "Jul" "Jul"
[2,]  "01"  "01"  "06"  "06"
[3,] "Dec" "Jun" "Dec" "Dec"
[4,]  "31"  "30"  "31"  "31"
[5,]  "00"  "12"  "09"  "09"
[6,]  "00"  "00"  "00"  "00"
[7,]  "24"  "18"  "19"  "19"
[8,]  "00"  "00"  "00"  "00"

表示:用“ - ”拆分每个单元格,然后将其转换为2行向量 我尝试使用here中的方法,但结果远离好,例如t(str_split_fixed(new_standard, "\\-", 8))

2 个答案:

答案 0 :(得分:2)

我们可以使用['fat', 'cat', 'hat', 'mat', 'sat', 'bat', 'lap']

中的scan
base R

答案 1 :(得分:1)

这是一个解决方案:

library(stringr)
matrix(t(str_split_fixed(df, "-", 2)), ncol = 4)
#      [,1]  [,2]  [,3]  [,4] 
# [1,] "Jan" "Jan" "Jul" "Jul"
# [2,] "01"  "01"  "06"  "06" 
# [3,] "Dec" "Jun" "Dec" "Dec"
# [4,] "31"  "30"  "31"  "31" 
# [5,] "00"  "12"  "09"  "09" 
# [6,] "00"  "00"  "00"  "00" 
# [7,] "24"  "18"  "19"  "19" 
# [8,] "00"  "00"  "00"  "00"