gpt4 book ai didi

r - 使用 lapply 列出 R 中每一列中空变量的百分比

转载 作者:行者123 更新时间:2023-12-04 12:19:13 24 4
gpt4 key购买 nike

我得到了一个 115 列和 1000 行的大型 csv。列有各种数据,有些是基于字符的,有些是整数等。但是,数据有很多不同类型的空变量(NA、-999、NULL 等)。

我想做的是编写一个脚本,该脚本将生成列的列表,其中列中超过 30% 的数据是某种类型的 NULL。

为此,我编写了一个脚本来为我提供一列的空百分比(十进制)。 这个脚本很适合我。

length(which(indata$ObservationYear == "" | is.na(indata$ObservationYear) |
indata$ObservationYear == "NA" | indata$ObservationYear == "-999" |
indata$ObservationYear == "0"))/nrow(indata)

我想编写一个脚本来为所有列执行此操作。我相信我需要使用 lapply 函数。

我试图在这里这样做,但是,我似乎根本无法让这个脚本工作:

Null_Counter <- lapply(indata, 2, length(x),
length(which(indata == "" | is.na(indata) | indata == "NA" | indata == "-999" | indata == "0")))
names(indata(which(0.3>=Null_Counter / nrow(indata))))

我收到以下错误:

Error in match.fun(FUN) : '2' is not a function, character or symbol

和:

Error: could not find function "indata"

理想情况下,我希望它给我的是所有列名称的向量列表,其中所有空变量(NA、-999、0、NULL)的百分比超过 30%。

有人可以帮忙吗?

最佳答案

我相信您想使用 apply 而不是 lapply 将函数应用于列表。试试这个:

Null_Counter <- apply(indata, 2, function(x) length(which(x == "" | is.na(x) | x == "NA" | x == "-999" | x == "0"))/length(x))
Null_Name <- colnames(indata)[Null_Counter >= 0.3]

关于r - 使用 lapply 列出 R 中每一列中空变量的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com