我正在使用函数from another thread,我希望在data.frame
中的每个list
上运行。我似乎无法正确设置索引,并且在reading this之后我可能需要将该函数保留在原始lapply
之外,但这并没有改善任何内容。
我的两个NAs数据框变成了一个列表:
df1 <- data.frame(
A = 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(
A = 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)
我在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")] # Only give me value of E
x # return x
})
我期望以下内容:
> dd
[[1]]
E
1 5
2 6
[[2]]
E
1 5
2 6
R从括号开始给出了这个错误(我已经尝试过只使用一个括号而不是两个,但同样的事情发生了):
> 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: could not find function "countNA"
>
> x = mylist[i][na_count < 2,]
Error: object 'i' not found
>
> x = x[, c("E")] # Only give me value of E
Error: object 'x' not found
>
> x # return x
Error: object 'x' not found
> })
Error: unexpected '}' in " }"
答案 0 :(得分:0)
尝试将countNA
功能修改为:
countNA <- function(list_entry) apply(list_entry, MARGIN = 1, FUN = function(x) length(x[is.na(x)]))
实际上,您将特定的子集列表作为参数,而函数应该采用一般参数,在您的情况下是一个列表。如何将该列表隔离以便传递给该函数在其他地方处理。