How can I access all objects of class data.frame inside .GlobalEnv in R

时间:2016-02-12 20:45:18

标签: r

I have 8,000 #include <stdio.h> int main() { int i, j; float amounts[5]; printf("Enter numbers as dollar amounts: \n"); for(i=0; i<5; i++) { printf("Value %d: ", i+1); scanf("%f", &amounts[i]); } long dollars[5]; long cents[5]; double decimal[5]; for (i=0; i<5; i++) { dollars[i]=trunc(amounts[i]); } for (i=0; i<5; i++) { printf("\n$%ld.", dollars[i]); decimal[i]=100*(amounts[i]-dollars[i]); cents[i]=(int)decimal[i]; if(cents[i]<10) printf("0%ld", cents[i]); else printf("%ld", cents[i]); } return 0; } s inside my global environment (data.frame) in R, for example

.GlobalEnv

How can I access each of the head(ls(.GlobalEnv)) #[1] "db1" "db2" "db3" "db4" "db5" tail(ls(.GlobalEnv)) #[1] "db7996" "db7997" "db7998" "db7999" "db8000" s?

I could access the data.frames using data.frame, but it is useless because I want to carry out a linear regression for each one.

4 个答案:

答案 0 :(得分:5)

You could use a combination of jps and eapply to put all mgets that are present in the global environment in a data.frame:

list

Then you can use for example x <- eapply(.GlobalEnv, 'is.data.frame') dflist <- mget(names(x[unlist(x)]), .GlobalEnv) to run a regression on each of them.


A very concise alternative approach contributed by @RichardScriven in the comments is:

lapply(dflist, ...)

答案 1 :(得分:1)

The simplest approach I can think of would be a basic Incompatible types! Required: com.stuff.Episode, Found: stuff.backend.appnameApi.model.Episode loop using for.

mget

You can then apply whatever operation you like on the for(df in ls(.GlobalEnv)){ print(get(df)) } result.

Note - this assumes the only variables in the environment are mget for your purposes as it doesn't discriminate A more restrictive data.frames loop would be:

for

which just uses for(df in ls(.GlobalEnv)){ if(is.data.frame(get(df))){ print(head(get(df))) } } to check if the object is indeed a is.data.frame.

答案 2 :(得分:0)

Perhaps:

File::Download

Can also restrict to only items beginning with 'db' using regex patterns

答案 3 :(得分:0)

我找到了另一个解决方案:

db1 <- data.frame(x = c(1,2,3),y = c(1.1,1.2,1.3))
db2 <- data.frame(x = c(1,2,3,4),y = c(2,2.1,2.2,2.3))
db3 <- data.frame(x = c(1,2,3,4,5),y = c(3,3.1,3.2,3.3,3.4))
ls()
#[1] "db1" "db2" "db3"
nombres <- ls()
eval(parse(text = nombres[1]))
#  x   y
#1 1 1.1
#2 2 1.2
#3 3 1.3
lm(y~x,data = eval(parse(text = nombres[1])))

谢谢!