简体   繁体   中英

How to loop a list through lappy after the $ sign in r

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!

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM