Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide and call an element of a list in R?

Tags:

list

r

Suppose I have a R list:

ls<-list(a="a",b="b",c="c")

Is there a way I can hide element b? such like:

> ls
$a
[1] "a"

$c
[1] "c"

And if it's hidden, how do I call it back like ls$b or ls$.b? I am asking this is because the element b may be very large and I don't want it list out but just used for the next analysis.

like image 596
David Z Avatar asked Dec 10 '25 05:12

David Z


2 Answers

you can also specify a new class and a new print function for your objet :

x <- vector("list", 3L)
names(x) <- letters[1:3]
x[[1]] <- 1
x[[2]] <- "the element to hide"
x[[3]] <- "a"
class(x) <- c("bob", "list")
attr(x, "hidden") <- "b"
print.bob <- function (x) {
    hid <- attr(x, "hidden")
    print(x[!names(x) %in% hid])
    }
x
$a
[1] 2

$c
[1] 4
# but
length(x)
[1] 3

hth

like image 97
droopy Avatar answered Dec 11 '25 20:12

droopy


Looks like you want to avoid printing element ls$b. These will work

ls<-list(a="a",b="b",c="c")
print(ls[-2])                      # print everything but second elememt
print(ls[which(names(ls)!="b")])   # print everything but element named "b"
like image 42
jlhoward Avatar answered Dec 11 '25 20:12

jlhoward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!