user1192748
user1192748

Reputation: 1015

R: How to create an array of character arrays

I am fairly new to R and I have to following situation. I got a text file with contents like this:

[1] a b c d e f g
[2] h i j k
[3] l m n o
[4] x y z

I want to group all characters, belonging to the same identifier ([x]) into an array. Since i want to access all characters of all identifiers, i will need to have a 2-dimensional array (an array of an array). This is what i tried:

> bigvector <- vector()
> bigvector <- append(bigvector, vector())
> bigvector[0][0] <- "Test"
> > bigvector[0][0]
logical(0)

So, no "Test" is returned. I also tried:

> tmpvector <- c("A", "B", "C", "D", "E", "F")
> bigvector <- vector()
> bigvector <- append(bigvector, tmpvector)
> bigvector[0][0]
character(0)

This should be an easy task, however I am struggling to accomplish it.

Upvotes: 2

Views: 8507

Answers (1)

Roland
Roland

Reputation: 132706

I am not sure what you want to do and whether you really need array objects.

I suggest to use lists. Here is an example assuming your [x] are just line numbers.

#read the data using readLines
tc <- textConnection("[1] a b c d e f g
[2] h i j k
[3] l m n o
[4] x y z")

dat <- readLines(tc)

#split at spaces
dat <- strsplit(dat,split=" ")

#remove identifier
rm1 <- function(x) x[-1] 
dat <- sapply(dat,rm1)

dat
#[[1]]
#[1] "a" "b" "c" "d" "e" "f" "g"
#
#[[2]]
#[1] "h" "i" "j" "k"
#
#[[3]]
#[1] "l" "m" "n" "o"
#
#[[4]]
#[1] "x" "y" "z"

dat[[3]][3]
#[1] "n"

Edit:

For the data given in the comment, you should use lapply.

dat <- readLines(file('http://pastebin.com/raw.php?i=tJW8H6K1'))

#split at spaces
dat <- strsplit(dat,split=" ")

#remove identifier
rm1 <- function(x) x[-1] 
dat <- lapply(dat,rm1)

#first five characters of the first line
dat[[1]][1:5]
#[1] "1" "1" "0" "1" "0"

Upvotes: 2

Related Questions