How to get the average of vectors in lists having same names inside for loop in R

Related searches

Here is the small example of what i am trying to do.

ex1 <- c(1,2,3)
nm <- c("cone","ctwo","cthree") 
names(ex1) <- nm

ex2 <- c(1.3,1.5,1.6)
names(ex2) <- nm

ex3 <- c(1.4,1.6,1.8)
names(ex3) <- nm

ex <- list(ex1,ex2,ex3)

for (i in seq(ex))
{
   ab<- ex[[i]]
}

The output i am getting is:

  ab
  cone   ctwo cthree 
  1.4    1.6    1.8

But the expected output should be something like this.

  ab
  cone   ctwo cthree 
  1.233    1.7    2.133

It gives the average values of cone ctwo and cthree from the three vectors in the list.

We can use colMeans after rbinding the list elements

colMeans(do.call(rbind, ex))
#    cone     ctwo   cthree 
#1.233333 1.700000 2.133333 

If we have objects created in the global environment with name starting with 'ex' followed by numbers, get all of them in a list with mget and then apply the code as above

colMeans(do.call(rbind, mget(ls(pattern = "ex\\d+")))) 

Or using Reduce

Reduce(`+`, ex)/length(ex)

Or using a for loop

n <- length(ex)
v1 <- numeric(n)
for(i in seq_along(ex)) v1 <- v1 + ex[[i]]
v1/m

Loops in R – Programming with R, In R you have multiple options when repeating calculations: vectorized analyze <- function(filename) { # Plots the average, min, and max inflammation over time. list.files(path = "data", pattern = "inflammation-[0-9]{2}.csv", full.names = TRUE) than the interpreted for loop because sum is coded in C to work with a vector� As a last step the vectors having the same columns are combined. do.call (rbind, listOfVectors) # or in full DF <- do.call (rbind, lapply (lapply (l, unlist), " [", unique (unlist (c (sapply (l,names)))))) The only little flaw in this function is that the column names of the first vector are taken as column names of the developing data frame.

Another way will be this:

> rowMeans(data.frame(ex))
    cone     ctwo   cthree 
1.233333 1.700000 2.133333

Chapter 8 Loops, Loop over a character vector with file names to read a set of input files. Loop over a numeric vector to calculate results for each of the values. This works for most R objects like vectors (and thus matrices), but also lists (and thus data.frames). The very same loop but “backwards” by using rev(participants) which reverses� Vector, Array, List and Data Frame in R Vector, Array, List and Data Frame are 4 basic data types defined in R. Knowing the differences between them will help you use R more efficiently. 1.

Name your list elements in ex:

ex <- list(ex1 = ex1, ex2 = ex2, ex3 = ex3)

then find the mean row-wise:

apply(as.data.frame(ex), 1, mean)

    cone     ctwo   cthree 
1.233333 1.700000 2.133333 

21 Iteration, Compute the mean of every column in mtcars . Determine the Output: we already have the output — it's the same as the input! Sequence: we Typically you'll be modifying a list or data frame with this sort of loop, so remember to use [[ , not [ . If you're creating named output, make sure to name the results vector like so:. The length function returns the length of R objects such as vectors, lists, or strings (find a little trick in Example 3). The R code above illustrates how to apply length in R. In this article, I’m going to provide 3 examples for the application of the length command in R. So without further ado, let’s get started…

Perhaps computationally slow but we can use plyr:

 sapply(plyr::ldply(ex),mean)
    cone     ctwo   cthree 
1.233333 1.700000 2.133333 

16 Loop Functions, You will get started with the basics of the language, learn how to manipulate This function takes three arguments: (1) a list X ; (2) a function (or the name of a You can put an arbitrarily complicated function definition inside lapply() , but if it's If the result is a list where every element is a vector of the same length (> 1),� Here, we show some simple examples of using a for-loop in R. Printing a list of numbers. Let's say we wanted to print a list of numbers from 0 to 3, inclusive. In R, the command 0:3 will create a vector with the numbers from 0 to 3, as you can see by entering that command at the R > command prompt: > 0:3 [1] 0 1 2 3

lapply: Apply a Function over a List or Vector, VALUE , in that they must have the same length and type. (Types may be promoted to a higher type within the ordering logical < integer < double < complex, but� What is R List? R list is the object which contains elements of different types – like strings, numbers, vectors and another list inside it. R list can also contain a matrix or a function as its elements. The list is created using the list() function in R. In other words, a list is a generic vector containing other objects. For example:

By Andrie de Vries, Joris Meys . You can extract components from lists in R. Consider two lists. The display of both the unnamed list baskets.list and the named list baskets.nlist show already that the way to access components in a list is a little different.

Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function. Creating a List. Following is an example to create a list containing strings, numbers, vectors and a logical values.

Comments
  • The solution suggested works only for this particular example but I have a large list having more than 100 elements generated. To enter all these manually will be tedious. That is the reason i want iterate over for loop.
  • It is not clear when you say that the list have more than 100 elements. It can have 100 or 1000 or 10000 elements, doesn't matter, the method suggested is to rbind the elements and then get the colMeans
  • Basically ex <- list(ex1,ex2,ex3) step will be done with mget(paste0("ex", 1:3)) or mget(ls(pattern = "^ex\\d+$"))
  • The solution you gave will work for this particular example. But the example i provided was very naive. I want to use for loop. My list is a very big list.
  • @AbhijeetPatil If the column names are the same. This would be more efficient than a for loop
  • I have a large list having more than 100 elements generated. To enter all these manually will be tedious. That is the reason i want iterate over for loop
  • @AbhijeetPatil Not sure why you need to enter manually, when you already have a list. If the objects are individually creaated then colMeans(do.call(rbind, mget(ls(pattern = "ex\\d+"))))
  • The for loop you suggested works perfectly fine in my case.