Home > OS >  loop through specific dataframe cell
loop through specific dataframe cell

Time:02-23

here is my problem: I have n dataframes (df1,df2,df3,df4,dn) from each dataframe, I would like to extract the value of the same cell: [2,3] and store it for later

I though this would work:

for (i in 1:n){
assign(paste0("v",i),get(paste0("df",i,"[2,3]")
}

but get is trying to get an object rather than the value of a cell (giving an error). Is there a function to do what I need?

Many thanks!

CodePudding user response:

The code in the get can be - i.e. get the whole object 'dfi' and extract the values based on i,j indexing. If we do get("dfi[2,3]"), it wouldn't work because there is no object named as that

for(i in seq_len(n)) {
    assign(paste0("v", i), get(paste0("df", i))[2,3]
}

As a small reproducible example

> data(mtcars)
> get("mtcars[1,2]")
Error in get("mtcars[1,2]") : object 'mtcars[1,2]' not found
> get("mtcars")[1,2]
[1] 6
  •  Tags:  
  • r
  • Related