list - Using lapply and the ifelse function in R -


i'm having issue in r can run ifelse statement on elements in list, place ifelse statement within lapply function, no longer works.

here's example. i'm working list of 3 dataframes:

> dflist [[1]]   id1 tid1 1  m1    1 2  m2    2 3  m3    3 4  m4    4 5  m5    5  [[2]]   id2 tid2 1  m7    7 2  m8    8 3  m9    9 4 m10   10 5 m11   11  [[3]]   id3 tid3 1 m13   13 2 m14   14 3 m15   15 4 m16   16 5 m17   17 6 m18   18 

if dataframe has odd number of rows, want r label "odd". if dataframe has number of rows, want r output same dataframe. output list.

this works when write standalone ifelse statements:

> ifelse(nrow(dflist[[1]])%%2==!0, "odd", dflist[1]) [1] "odd"  > ifelse(nrow(dflist[[3]])%%2==!0, "odd", dflist[3]) [[1]]   id3 tid3 1 m13   13 2 m14   14 3 m15   15 4 m16   16 5 m17   17 6 m18   18 

but error message put lapply statement.

> lapply(dflist, function(x) ifelse(nrow(dflist[[x]])%%2==!0, "odd", dflist[x]))   error in dflist[[x]] : invalid subscript type 'list'  >  

any ideas why happens , how fix it? thank you

if need return either "odd" or dataset, use if/else

lapply(dflist, function(x) if(nrow(x)%%2==1) "odd" else x) 

data

dflist <- list(data.frame(col1 = 1:3, col2=4:6), data.frame(col1=1:4, col2=5:8)) 

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -