Reputation: 745
I have a list consist of 23 elements with 69 rows and 13 columns each. And I need to apply calculation on multiple columns for each element of the list.
As a simple example, my list looks like this:
>list
>$`1`
> a b c
>1 2.1 1.4 3.4
>2 4.4 2.6 5.5
>3 2.6 0.4 3.0
...
>$`2`
> a b c
>70 5.1 4.9 5.1
>71 4.4 7.6 8.5
>72 2.8 3.5 6.8
...
what I wish to do is something like z = (a-b) / c
for each element ($1
,$2
..., $23
)
I tried the following code:
for( i in 1:23) {
z = (list[[i]]$a - list[[i]]$b) / list[[i]]$c }
which gave me only 49 values, rather than 1566 values.
Anyone have any idea what was wrong with my code and be able to correct it? Thank you very much!
Upvotes: 1
Views: 2501
Reputation: 12829
Working on @DidzisElferts answer, you can use this
lapply(ll, within, z <- (a-b)/c)
to add z
as a new column on each dataframe.
Upvotes: 2
Reputation: 98599
You can do it with function lapply()
. Here is example assuming that in all data frame columns have the same name.
ll<-list(data.frame(a=1:3,b=4:6,c=7:9),
data.frame(a=1:3,b=6:4,c=7:9),
data.frame(a=1:3,b=4:6,c=9:7))
lapply(ll, with, (a-b)/c)
Upvotes: 3