如何在R中不同字符串列的列中拆分长字符串?

时间:2017-10-31 23:29:10

标签: r string split

如果矩阵的第一列是长字符串,如何将其拆分为不同的字符串列?或实例:

     V1    V2   V3

a-b-c-d  1000  100

e-f-g-h  1100  110

并获得:

     V1    V2   V3   V4   V5   V6

      a     b    c    d  1000  100

      e     f    g    h  1100  110

1 个答案:

答案 0 :(得分:1)

# Your sample data
df <-  cbind.data.frame(
    V1 = c("a-b-c-d", "e-f-g-h"),
    V2 = c(1000, 1100),
    V3 = c(100, 110), stringsAsFactors = FALSE);

那里......

# Split and cbind new and old columns
df <- cbind.data.frame(
    do.call(rbind.data.frame, strsplit(df[, 1], "-")),
    df[, -1])
colnames(df) <- paste("V", seq(1:ncol(df)), sep = "");

df;
#  V1 V2 V3 V4   V5  V6
#1  a  b  c  d 1000 100
#2  e  f  g  h 1100 110

......然后再回来

# Concatenate columns 1-4
df <- cbind.data.frame(
    V1 = apply(df[, 1:4], 1, paste, collapse = "-"),
    df[, -(1:4)]);
colnames(df) <- paste("V", seq(1:ncol(df)), sep = "");    
df;
#       V1   V2  V3
#1 a-b-c-d 1000 100
#2 e-f-g-h 1100 110