1

Question about :

I have a string vector foo:

>foo = c("1x2","3x4","5x6","7x8","9x10")

I split the individual strings over the “x” and stick the result in goo:

>goo = strsplit(foo, "x")
>goo
[[1]]
[1] "1" "2"

[[2]]
[1] "3" "4"

[[3]]
[1] "5" "6"

[[4]]
[1] "7" "8"

[[5]]
[1] "9"  "10"

How do I extract the first and second ‘column’ from this list? (I want (1,3,5,7,9) and (2,4,6,8,10))

Rene Reitsma
  • 31
  • 1
  • 6

5 Answers5

7

Use sapply to serially 'extract' using "[[":

 sapply(goo, "[[" , 1)
[1] "1" "3" "5" "7" "9"

I've always thought that should be the result, but I probably don't understand the issues.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
1
> result <-  do.call(rbind, goo)
> result
     [,1] [,2]
[1,] "1"  "2" 
[2,] "3"  "4" 
[3,] "5"  "6" 
[4,] "7"  "8" 
[5,] "9"  "10"
> result[, 1] # column 1
[1] "1" "3" "5" "7" "9"
> result[, 2] # column 2
[1] "2"  "4"  "6"  "8"  "10"
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

The easiest way is to wrap the results in an sapply statement

odd_results <- sapply(goo, function(x) x[1])

and

even_results <- sapply(goo, function(x) x[2])
Melissa Key
  • 4,476
  • 12
  • 21
0

Overview

You'll need to specify the extraction of the list elements by position.

# load data
foo <- c("1x2","3x4","5x6","7x8","9x10")

# split foo by 'x'
foo.list <- strsplit( x = foo, split = "x", fixed = TRUE )

# store the first and second elements of each list in a data frame
foo.df <-
data.frame(
    First_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 1 ) )
    , Second_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 2 ) )
  )
Cristian E. Nuno
  • 2,822
  • 2
  • 19
  • 33
0

For the sake of variety, you could use

goo <- unlist(strsplit(foo, "x"))

a <- goo[seq(1, length(goo), 2)]
b <- goo[seq(2, length(goo), 2)]

Which yields

[1] "1" "3" "5" "7" "9"

and

[1] "2"  "4"  "6"  "8"  "10"

respectively.

Jan
  • 42,290
  • 8
  • 54
  • 79