Übel Yildmar
Übel Yildmar

Reputation: 491

How to save the first element of a row from a list to a new variable?

I got a list variable 'bracket', which dimensions are n x m, where n denotes the rows, and m denotes the number of elements in the given row. However, n is constant, but m varies.

> bracket
[[1]]
[1] 8

[[2]]
[1] 11 22

[[3]]
[1] 13 25

[[4]]
[1] 18

I would like to see the following:

> bracket
[1]  8 11 13 18

How can I do that? Thank you for your help!


After using sapply(bracket, '[[', 1), I had some trouble. I got the following error:

Error in FUN(X[[i]], ...) : subscript out of bounds. What to do if I have got some rows with no value/NA?

Upvotes: 0

Views: 213

Answers (1)

jogo
jogo

Reputation: 12569

I produced a data example on my own to reproduce the error:

bracket <- list(8, c(11, 22), c(13, 25), 18)
sapply(bracket, '[[', 1) # will not reproduce the error
sapply(bracket, '[', 1)  # will not reproduce the error

bracket <- list(8, c(11, 22), numeric(0), c(13, 25), 18)
sapply(bracket, '[[', 1)  # will reproduce the error
sapply(bracket, '[', 1)   # gives NA

na.omit(sapply(bracket, '[', 1)) # omits the NAs

Upvotes: 1

Related Questions