Reputation: 267
I have a bunch of data frames named Ldat.1, Ldat.2, etc., in my normal R environment that I can access interactively.
From the console, I can type:
> dim(Ldat.1)[1]
[1] 40
> dim(Ldat.2)[1]
[1] 39
So I can tell that the first has 40 rows and the second has 39 rows.
However, with dozens of data frames, I want to write a script to tell me how many rows are in each frame.
I tried the following:
print(dim(Ldat.1)[1])
print(dim(Ldat.2)[1])
for (i in 1:2){
namex<-paste("Ldat.",i,sep="")
size<-dim(.GlobalEnv$namex)
print(size[1])
}
and the console showed:
> print(dim(Ldat.1)[1])
[1] 40
> print(dim(Ldat.2)[1])
[1] 39
> for (i in 1:2){
+ namex<-paste("Ldat.",i,sep="")
+ size<-dim(.GlobalEnv$namex)
+ print(size[1])
+ }
NULL
NULL
It's easy enough to construct the strings:
for (i in 1:2){
namex<-paste("Ldat.",i,sep="")
size<-dim(namex)
print(namex)
}
produces:
> for (i in 1:2){
+ namex<-paste("Ldat.",i,sep="")
+ size<-dim(namex)
+ print(namex)
+ }
[1] "Ldat.1"
[1] "Ldat.2"
But despite trying various combinations of "as.data.frame" and "envir=" I can't seem to get R to interpret the string "Ldat.1" as meaning the name of an object accessible from the console.
Thanks in advance.
Upvotes: 0
Views: 55
Reputation: 263332
Try this instead:
for (i in 1:2){
namex<-paste("Ldat.",i,sep="")
size<-dim(.GlobalEnv[[namex]])
print(size[1])
}
The problem has nothing to do with environments and everything to do with the fact that $
does not evaluate its second argument (it's first argument being the token name that precedes it, .GlobalEnv
in this case). There is no object in .GlobalEnv
named "namex". On the other hand "[[" does an evaluation step, so the value of namex
(which is "Ldat.1" during the first pass of the for-loop) will get substituted and lookup will succeed.
Upvotes: 2
Reputation: 269501
1) This will list the names of each data frame and the number of rows it has:
sapply(Filter(is.data.frame, mget(ls())), nrow)
If we already had nms
, a vector of names of data frames, then we could reduce this to:
nms <- c("Ldat.1", "Ldat.2")
sapply(mget(nms), nrow)
2) Here is another way:
simplify2array(Filter(Negate(is.null), eapply(.GlobalEnv, nrow)))
3) Also try the ll
function in the R.oo package.
Upvotes: 4