In R, use a function apply() inside of lapply that is working over a list of data frames -
i using function from thread, want run on every data.frame
in list
. can't seem set indexing correctly, , after reading this thought maybe needed leave function outside of original lapply
, didn't improve anything.
my 2 data frames nas turned list:
df1 <- data.frame( = c(1, 2, 3, na), b = c(1, 2, na, na), c = c(1, na, na, na), e = c(5, 6, 7, 8) ) df2 <- data.frame( = c(1, 2, 3, na), b = c(1, 2, na, na), c = c(1, na, na, na), e = c(5, 6, 7, 8) ) mylist <- list(df1, df2)
my function inside of lapply:
dd <- lapply(seq_along(mylist), function(i){ countna <- function(mylist[[i]]) apply(mylist[[i]], margin = 1, fun = function(x) length(x[is.na(x)])) df_mos <- subset(mylist[[i]], select = c("a", "b", "c")) na_count <- countna(df_mos) x = mylist[[i]][na_count < 2,] x = x[, c("e")] # give me value of e x # return x })
for expect following:
> dd [[1]] e 1 5 2 6 [[2]] e 1 5 2 6
r gives me error beginning bracket (and i've tried using 1 bracket instead of two, same thing occurs):
> dd <- lapply(seq_along(mylist), function(i){ + + countna <- function(mylist[i]) apply(mylist[i], margin = 1, fun = function(x) length(x[is.na(x)])) error: unexpected '[' in: " countna <- function(mylist[" > > df_mos <- subset(mylist[i], select = c("a", "b", "c")) error in subset(mylist[i], select = c("a", "b", "c")) : object 'i' not found > > na_count <- countna(df_mos) error: not find function "countna" > > x = mylist[i][na_count < 2,] error: object 'i' not found > > x = x[, c("e")] # give me value of e error: object 'x' not found > > x # return x error: object 'x' not found > }) error: unexpected '}' in " }"
try modifying countna
function this:
countna <- function(list_entry) apply(list_entry, margin = 1, fun = function(x) length(x[is.na(x)]))
as is, taking specific subsetted list argument, whereas function should take general argument, in case list. how list being isolated in order pass function handled elsewhere.
Comments
Post a Comment