0

A little confused with how I am trying to acheive the results I want.

I have an environment in R which consists of 5 data.frames called df[i]

So;

df1
df2
df3
df4
df5

Inside of these df´s I have 5 columns called col[j]

col1
col2
col3
col4
col5

In total I have 25 columns across 5 data frames (5 df x 5 col).

I also have a static variable called R which is a vector of numbers

I am trying to calculate for each column of each dataframe a basic formula using a function/loop. The formula for column 1 of df1 would be;

Y = df1$col1 - R

I am trying to calculate this and repeat for each colum[j:5] in df[i:5] and store it in a new data.frame

j <- 1:5
i <- 1:5
fun <- function(x){
  for(i in 1:col[j](df[i])){
    Y[j] <- col[j] - R
  }
}

EDIT: Added comment below for easier reading.

Y1a = df1$col1 - R
Y2a = df1$col2 - R
Y3a = df1$col3 - R  
..... 

.....
 Y1b = df2$col1 - R 
 Y2b = df2$col2 - R 
 Y3b = df2$col3 - R
..... etc
user113156
  • 5,113
  • 4
  • 22
  • 46
  • I don't fully understand what you want to do. A good start would be using `dplyr::mutate_each(df1, function(x) x - R)` – Flo.P Dec 01 '17 at 14:46
  • Okay, so I want to calculate the formula `Y = df[i]$col[j] - R` across all 5 dataframes and all columns, for example; `Y1a = df1$col1 - R` | `Y2a = df1$col2 - R` | `Y3a = df1$col3 - R` ..... and .... `Y1b = df2$col1 - R` | `Y2b = df2$col2 - R` | `Y3b = df2$col3`.... etc – user113156 Dec 01 '17 at 14:48
  • 1
    Do you really want a for loop or this is what you've tried so far? What @Flo.P suggested is one of the ways to do it, but you have to apply that process to each of your datasets. – AntoniosK Dec 01 '17 at 14:56

2 Answers2

3
# Put your data in a list:    
dflist = mget(paste0("df", 1:5))

# Apply your function to every data frame
ylist = lapply(dflist, function(x) x - R)

# Name the resulting columns y1:y5
ylist = lapply(ylist, setNames, paste0("y", 1:5))

Have a look at How to make a list of data frames for examples and discussion of why using lists is better.

Gregor Thomas
  • 104,719
  • 16
  • 140
  • 257
1

tidyverse version

dplyr::mutate_all apply a fonction to each column of a data.frame.

So I would do like that:

all_df <- list(df1, df2, df3, df4, df5) 
map(all_df, function(x) mutate_all(x, function(y) y - R))    

It should return you a list of length 5. Each df contains your desired statistic.

Flo.P
  • 351
  • 1
  • 7