Skip to content

How to split a character vector into 3 vectors

8 messages · kayj, Jorge Ivan Velez, Nordlund, Dan (DSHS/RDA) +5 more

#
Hi ,


Does any one know how to split a character vector , I have a vector X that
looks like this and each row has 3 characters

  X
ASK
DGH
ASG
AUJ
FRT

I would like to split the vector into 3 vectors that look like this

X1	X2	X3
A  	S	K
D	G	H
A	S	G
A	U	J
U	R	T

thanks
#
See ?strsplit

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA  98504-5204
#
kayj wrote:
If I understand you correctly, you have this vector:

x <- c("ASK", "DGH", "ASG", "AUJ", "URT")

This code seems to do what you want:

x1 <- substr(x, 1, 1)
x2 <- substr(x, 2, 2)
x3 <- substr(x, 3, 3)

There's probably a much simpler and more elegant way to do it, though.
#
kayj wrote:
# dummy example data
n = 3
x = replicate(10, paste(sample(letters, n), collapse=""))

y = lapply(1:n, function(i) substr(x, i, i))

# if you need a specific vector
x1 = y[[1]]

# if you really need all three as separate variables
for (i in 1:n)
    assign(paste('x', i, sep=""), y[[i]])

vQ
#
This splits them into a 3 column matrix:
[,1] [,2] [,3]
[1,] "A"  "S"  "K"
[2,] "D"  "G"  "H"
[3,] "A"  "S"  "G"
[4,] "A"  "U"  "J"
[5,] "U"  "R"  "T"

z[,1], z[,2] and z[,3] are your vectors.
On Tue, Feb 10, 2009 at 1:50 PM, kayj <kjaja27 at yahoo.com> wrote:
#
someone has probably answered this already but use
substr()
new variable<-substr(old.variable,1,1)

Simon.

----- Original Message ----- 
From: "kayj" <kjaja27 at yahoo.com>
To: <r-help at r-project.org>
Sent: Tuesday, February 10, 2009 6:50 PM
Subject: [R] How to split a character vector into 3 vectors