PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] how to append an element to a list without keeping track of the index?

 May 13, 2022     append, list, r     No comments   

Issue

I am looking for the r equivalent of this simple code in python

mylist = []
for this in that:
  df = 1
  mylist.append(df)

basically just creating an empty list, and then adding the objects created within the loop to it.

I only saw R solutions where one has to specify the index of the new element (say mylist[[i]] <- df), thus requiring to create an index i in the loop.

Is there any simpler way than that to just append after the last element.


Solution

There is a function called append:

ans <- list()
for (i in 1992:1994){
n <- 1 #whatever the function is
ans <- append(ans, n)
}

  ans
## [[1]]
## [1] 1
## 
## [[2]]
## [1] 1
## 
## [[3]]
## [1] 1
## 

Note: Using apply functions instead of a for loop is better (not necessarily faster) but it depends on the actual purpose of your loop.

Answering OP's comment: About using ggplot2 and saving plots to a list, something like this would be more efficient:

plotlist <- lapply(seq(2,4), function(i) {
            require(ggplot2)
            dat <- mtcars[mtcars$cyl == 2 * i,]
            ggplot() + geom_point(data = dat ,aes(x=cyl,y=mpg))
})

Thanks to @Wen for sharing Comparison of c() and append() functions:

Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors.



Answered By - M--
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing