Reputation: 55
I have a list like:
foo<- list(c("foob.10.27808", "foob.11.31809","foob.12.35810","foob.13.39811",
"foob.14.43812", "foob.15.47813", "foob.16.51814", "foob.17.<NA>",
"foob.5.7803", "foob.6.11804", "foob.7.15805", "foob.8.19806",
"foob.9.23807")
Now I want to remove the object with the name "foob.17.<NA>
. This should be no problem if I want to do it manually like foo$foob.17.<NA><-NULL
or if I would exacly know what its name is, but first I don't want to do it manually (of course not ;)) and second, I don't know its name in every case.
Those lists are created inside a function so the only part of its name I do know is ".<NA>"
.
Is there a way to find the name only by matching it with ".<NA>"
an remove it afterwards? Like it's done with environment elements with rm(list=ls(pattern="foo"))
?
Thank you in advance.
Best regards, Chris
Upvotes: 0
Views: 51
Reputation: 269481
Actually foo$"foob.17.<NA>" <- NULL
will not work because the list has no component with the name "ffoob.17.<NA>"
. The list has only one component and that component contains a character vector.
grep
can be used:
list(grep(".<NA>", foo[[1]], value = TRUE, invert = TRUE, fixed = TRUE))
## [[1]]
## [1] "foob.10.27808" "foob.11.31809" "foob.12.35810" "foob.13.39811"
## [5] "foob.14.43812" "foob.15.47813" "foob.16.51814" "foob.5.7803"
## [9] "foob.6.11804" "foob.7.15805" "foob.8.19806" "foob.9.23807"
If you meant to write foo2
where foo2
is shown below then we can use Filter
:
foo2 <- as.list(foo[[1]])
Filter(function(x) !grepl(".<NA", x, fixed = TRUE), foo2)
or if you meant you have a list whose names are the character vector foo[[1]]
as shown below then:
foo3 <- setNames(as.list(seq_along(foo[[1]])), foo[[1]])
foo3[ grep(".<NA>", names(foo3), invert = TRUE, fixed = TRUE) ]
Note: foo
in the question had unbalanced parentheses so here it is in reproducible form with that fixed:
foo<- list(c("foob.10.27808", "foob.11.31809","foob.12.35810","foob.13.39811",
"foob.14.43812", "foob.15.47813", "foob.16.51814", "foob.17.<NA>",
"foob.5.7803", "foob.6.11804", "foob.7.15805", "foob.8.19806",
"foob.9.23807"))
Upvotes: 3