Home > Software design >  Covert one character into one column
Covert one character into one column

Time:07-22

I have text files I want to convert one character into one column. I tried with strplit but didn't get desired output.

test1.txt
ATTGCATGTACGTATCGTTGAC

test2.txt
ACCCGCGGGGNNCGTATCGAAGAC

expected output

test1.txt

V1 V2 V3 V4 V5 ...
A   T T  G   C

test2.txt
V1 V2 V3 V4 V5 ...
A  C  C   C  G

CodePudding user response:

strsplit option and changing the columnames to V1 etc like this:

test1.txt <- c("ATTGCATGTACGTATCGTTGAC")
output <- data.frame(do.call(rbind, strsplit(test1.txt, "")))
names(output) <- paste0("V", 1:length(output))
output
#>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
#> 1  A  T  T  G  C  A  T  G  T   A   C   G   T   A   T   C   G   T   T   G   A
#>   V22
#> 1   C

Created on 2022-07-21 by the reprex package (v2.0.1)

CodePudding user response:

string <- readLines('test1.txt')
as.data.frame(t(strsplit(string, '')[[1]]))

  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22
1  A  T  T  G  C  A  T  G  T   A   C   G   T   A   T   C   G   T   T   G   A   C
  • Related