如何在R中创建一个函数来检查数据错误?
我有很多csv文件的温度数据,我导入到R处理。这些文件看起来像:如何在R中创建一个函数来检查数据错误?,r,function,data-cleaning,R,Function,Data Cleaning,我有很多csv文件的温度数据,我导入到R处理。这些文件看起来像: ID Date.Time temp1 temp2 1 08/13/17 14:48:18 15.581 -0.423 2 08/13/17 16:48:18 17.510 -0.423 3 08/13/17 18:48:18 15.390 -0.423 有时,第3列和第4列中的温度读数明显错误,必须用NA值替换。我知道任何超过50或低于50的都是错误的。我想马上把这些拿走
ID Date.Time temp1 temp2
1 08/13/17 14:48:18 15.581 -0.423
2 08/13/17 16:48:18 17.510 -0.423
3 08/13/17 18:48:18 15.390 -0.423
有时,第3列和第4列中的温度读数明显错误,必须用NA值替换。我知道任何超过50或低于50的都是错误的。我想马上把这些拿走。使用
df[,c(3,4)]<- replace(df[,c(3,4)], df[,c(3,4)] >50, NA)
df[,c(3,4)] <- replace(df[,c(3,4)], df[,c(3,4)] < -50, NA)
df[,c(3,4)]50,NA)
df[,c(3,4)]您需要在remove.errors
中返回df
;您还可以使用abs
更简洁地编写replace
语句:
remove.errors<-function (df) {
df[]<- replace(df, abs(df) > 50, NA)
return(df)
}
1)试试这个。它只使用基本R
clean <- function(x, max = 50, min = -max) replace(x, x > max | x < min, NA)
df[3:4] <- clean(df[3:4])
2)加入magrittr,我们可以做到:
library(magrittr)
df[3:4] %<>% { clean(.) }
library(dplyr)
df %>% mutate_at(3:4, clean)
如果data.frame中有非数字列,则可能需要:
remove_errors <- function(df) {
numcols <- sapply(df, is.numeric)
df[ , numcols] <- lapply(df[,numcols], function(x) ifelse(abs(x) > 50, NA, x))
return(df)
}
remove\u错误使用lappy(df[3:4],clean)
会更好吗?它不会经过转换成矩阵。然而,对于大小帧,lappy
版本需要一半的时间(基准测试高达5e5行)。对我来说,问题不在于性能,而在于看到一些习惯会在某个时候(不是在这里)伤害毫无戒心的程序员,例如,在具有不同列类的data.frame
上使用apply(MARGIN=1,…)
。实际上clean(df[3:4])
生成一个data.frame,而不是一个矩阵。好的,那么class(x>max | x
是matrix
,这是另一回事。很抱歉,我没有说你的代码不好或工作不好。
transform(df, temp1 = clean(temp1), temp2 = clean(temp2))
library(magrittr)
df[3:4] %<>% { clean(.) }
library(dplyr)
df %>% mutate_at(3:4, clean)
remove_errors <- function(df) {
numcols <- sapply(df, is.numeric)
df[ , numcols] <- lapply(df[,numcols], function(x) ifelse(abs(x) > 50, NA, x))
return(df)
}
set.seed(1234)
mydf <- data.frame(
a = sample(-100:100, 20, T),
b = sample(30:70, 20, T),
c = sample(letters, 20, T),
stringsAsFactors = F
)
remove_errors(mydf)