Reputation: 903
I loaded some objects into R workspace (of rstudio) and tried assigning to a variable (like this: x <- list("regular expression pattern forobjectName") so that the contents will be available for further analysis using merge function. R simply assigned the correct object name surrounded by quotes and merge() threw error when I passed x to it. Does anyone know which functions might be useful for reading the object which can then be assigned to a variable for further analysis?
Thanks
Upvotes: 0
Views: 372
Reputation: 2088
The get()
function retrieves an object by name. Thus, if x
is 1, you can use get("x")
to get 1 :
> # Typing this on the R command line...
> x <- 1
> get("x")
[1] 1
You could use get()
as part of an lapply()
on a list of variable names to retrieve all objects that match the pattern you are looking for. Here's example in which I merge()
two data frames retrieved indirectly.
The x <- lapply(ls(pat="^df"), get)
is the core statement relevant to you.
> # First we define the data frames
> df1 <- data.frame(a=1:5, b=1:5)
> df2 <- data.frame(a=3:7, b=3:7)
> ls(pat="^df")
[1] "df1" "df2"
> # This just gets their names
> x <- ls(pat="^df")
> x
[1] "df1" "df2"
> # This retrieves the actual objects
> x <- lapply(ls(pat="^df"), get)
> x
[[1]]
a b
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
[[2]]
a b
1 3 3
2 4 4
3 5 5
4 6 6
5 7 7
> merge(x[[1]], x[[2]])
a b
1 3 3
2 4 4
3 5 5
Upvotes: 2