user3069326
user3069326

Reputation: 575

Read string into a table

if the data which I want to import into R looks like this

kljflksdjfklsdjfsdfj
dfjkdsjfkdjfkldjfkjd
djfkdsjfkdjfjsdfjsdk
dsjfkjsdfkdjsfkjdskj

and I would like to read them in such a way that I get a matrix out of it with each sign being a column ( first column would be k,d,d,d) and each new line a row (4 rows in my case). How can I do that?

Upvotes: 2

Views: 302

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You could also use read.fwf. Replace "yourFileName" with the name of your actual file, of course.

read.fwf(file="yourFileName", 
         widths = rep(1, nchar(readLines("yourFileName", n=1))))
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
# 1  k  l  j  f  l  k  s  d  j   f   k   l   s   d   j   f   s   d   f   j
# 2  d  f  j  k  d  s  j  f  k   d   j   f   k   l   d   j   f   k   j   d
# 3  d  j  f  k  d  s  j  f  k   d   j   f   j   s   d   f   j   s   d   k
# 4  d  s  j  f  k  j  s  d  f   k   d   j   s   f   k   j   d   s   k   j

The output here is a data.frame.

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

You can use scan to read the file:

text <- "kljflksdjfklsdjfsdfj
dfjkdsjfkdjfkldjfkjd
djfkdsjfkdjfjsdfjsdk
dsjfkjsdfkdjsfkjdskj"    

dat <- scan(textConnection(text), "")
# dat <- scan("file.name", "")

The function strsplit splits the strings into single characters. rbind is used to create the matrix:

do.call(rbind, strsplit(dat, ""))

The result:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] "k"  "l"  "j"  "f"  "l"  "k"  "s"  "d"  "j"  "f"   "k"   "l"   "s"   "d"   "j"   "f"   "s"   "d"   "f"   "j"  
[2,] "d"  "f"  "j"  "k"  "d"  "s"  "j"  "f"  "k"  "d"   "j"   "f"   "k"   "l"   "d"   "j"   "f"   "k"   "j"   "d"  
[3,] "d"  "j"  "f"  "k"  "d"  "s"  "j"  "f"  "k"  "d"   "j"   "f"   "j"   "s"   "d"   "f"   "j"   "s"   "d"   "k"  
[4,] "d"  "s"  "j"  "f"  "k"  "j"  "s"  "d"  "f"  "k"   "d"   "j"   "s"   "f"   "k"   "j"   "d"   "s"   "k"   "j"  

Upvotes: 2

Related Questions