-2

If my first column of a matrix is a long string, how can I split it in different string columns? or instance:

     V1    V2   V3

a-b-c-d  1000  100

e-f-g-h  1100  110

and obtain:

     V1    V2   V3   V4   V5   V6

      a     b    c    d  1000  100

      e     f    g    h  1100  110
  • https://stackoverflow.com/questions/8464312/convert-comma-separated-entry-to-columns or https://stackoverflow.com/questions/4350440/split-a-column-of-a-data-frame-to-multiple-columns or https://stackoverflow.com/questions/18641951/splitting-a-dataframe-string-column-into-multiple-different-columns or ... – thelatemail Oct 31 '17 at 23:41

1 Answers1

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);

There ...

# 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

... and back again

# 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
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68