Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a list from ls(pattern="") [R]

Tags:

list

r

The ls(pattern="") function is very useful for me, since my list of objects seem to keep growing and growing. I am curious if this feature can be more useful.

For example, let's say i have 4 objects,

a.c<-1
b.c<-2
c.c<-3
d.c<-4

Now i use the useful ls(pattern="") function

ls(pattern=".c")

Now i try to make a list

list(ls(patter=".c"))

But it doesn't give me anything useful( "a.c" "b.c" "c.c" "d.c" ). I want either of these two outputs

1,2,3,4

OR

a.c, b.c, c.c, d.c
like image 876
MadmanLee Avatar asked Dec 20 '22 14:12

MadmanLee


1 Answers

A couple of issues:

1) The . in ".c" gets ignored, you need to "escape" it:

ls(pattern="\\.c")

Otherwise it will return all objects with c regardless of having a period.

2) ls returns names of objects as character. To get the value of an object based on its name you need the function get:

lapply(ls(pattern="\\.c"), get)

3) As joran mentioned in the comments, it's much better to keep objects associated with each other in lists:

List.c = list(a.c=1, b.c=2, c.c=3, d.c=4)
like image 167
Señor O Avatar answered Jan 09 '23 15:01

Señor O