0

I have been trying to figure out how to apply the apply functions plyr is out there. I will learn that later. But, I need help. I can get output with actually typing the object name in, but I am trying to loop a list through it. The code is as follows:

    list<-noquote(c("T","AAVL"))
lapply(list,function(i) xts(l.df$i[,-1:-5],order.by=as.POSIXct(rownames(l.df$i))))

If I just do xts(l.df$T[,-1:-5],order.by=as.POSIXct(rownames(l.df$T))

I get the xts file that I need. Could someone please help me loop the names without quotes into the lapply(), so that I could have this work for numerous elements in my list? Thank you!

dragon
  • 88
  • 8
  • 1
    You should provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we know exactly what your object looks like. You can't use `$` with variables for field names. Try `l.df[[i]]` instead. – MrFlick Jun 21 '15 at 04:57
  • I would, but there is a lot of data. I will try l.df[[i]] thanks! – dragon Jun 21 '15 at 05:08
  • Hey @MrFlick Just want to say thanks... `lapply(list,function(i) xts(l.df[[i]][,-1:-5],order.by=as.POSIXct(rownames(l.df[[i]]))))` worked out for me thank god I knew what I was doing, experimenting. Anyways, I learned how to apply the apply function. It is basically an iterator for the number of elements. Therefore, I understand how field names cannot be used in the apply functions. – dragon Jun 21 '15 at 05:35

2 Answers2

0

There are a number of ways to subset a list in R. See https://ramnathv.github.io/pycon2014-r/learn/subsetting.html or http://adv-r.had.co.nz/Subsetting.html for more detailed discussion.

However, in your case the issue is that the dollar operator $ takes a fixed string rather than a variable name. So myList[["item"]] and myList$item are equivalent. In the example you gave, you're trying to find the member of the data.frame called "i", not the one referenced by the variable i. The noquote class you used purely affects printing of a character vector; it has no effect on subsetting.

The version of your code that works doesn't work as you explain in your comment. It works because you're now subsetting the column whose name is stored in i not the one called "i".

Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
0

I want to add 106 new columns to a dataframe that are the length of the df ofcourse and filled with zeros (0). How would I loop over i in this case:

geo <- unique(df$geo)

geo
[1] "AL" "AT1" "AT2" "AT3" "BE1" "BE2" "BE3"

for(i in geo) {
 df$i <- v(0,length(df)
} 

Emil Krabbe 2 mins ago Edit

Emil Krabbe
  • 101
  • 9