简体   繁体   English

在R中处理聚合函数中的NA

[英]Handling NA's in aggregate function in R

I am trying to get the daily sum from a csv file using the aggregate function but I am encountering the following errors: 我正在尝试使用聚合函数从csv文件获取每日总和,但是遇到以下错误:

Error in Summary.factor(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), na.rm = FALSE) : ‘sum’ not meaningful for factors
Calls: aggregate ... aggregate.data.frame -> lapply -> FUN -> lapply ->          Summary.factor 
Execution halted

Here is the link to the data Data 这里是链接到的数据资料

Here's my code: 这是我的代码:

dat<-read.csv("Laoag_tc_induced.csv",header=TRUE,sep=",")
dat[dat == -999] <- NA
dat[dat == -888] <- 0
dat$Date <- as.Date(strptime(dat$key, '%Y_%m_%d_%H'))

df <- data.frame(dat$Date,dat$RR,dat$dist)
df <- aggregate(RR ~ Date, dat,sum)

names(df)[1] <- "Date"
names(df)[2] <- "Rain"

write.table(df,file="test.csv",sep=",")

I tried using: 我尝试使用:

df <- aggregate(RR ~ Date, dat,sum,na.rm=TRUE)

and

df <- aggregate(RR ~ Date,dat,sum,na.rm=TRUE,na.action=na.pass)

The error is still the same: 错误仍然相同:

‘sum’ not meaningful for factors

There are certain elements in the 'RR' ie " NA" , changed the class of the column to factor (also use stringsAsFactors = FALSE ). “ RR”中有某些元素,即" NA" ,将列的类别更改为要stringsAsFactors = FALSE factor (也使用stringsAsFactors = FALSE )。 The option would be to specify the NA strings within na.strings to be read as NA 该选项将在na.strings指定NA字符串,以将其读取为NA

dat <- read.csv(file, header = TRUE, stringsAsFactors = FALSE, 
          na.strings = "   NA", strip.white = TRUE)

After doing the OP's transformation/replacement, 完成OP的转换/替换后,

res <- aggregate(RR ~ Date, dat,sum)
head(res, 5)
#        Date  RR
#1 1994-08-09 0.0
#2 1994-08-10 0.0
#3 1994-08-11 0.0
#4 1994-08-12 0.3
#5 1994-08-13 0.0

As the OP stated that the date are getting changed, it is working fine based on the data provided 由于OP指出日期正在更改,因此根据提供的数据可以正常工作

dat[78:81,]
#   X.1          key     SN CY     Lat.x    Lon.x     X   RR     Lat.y    Lon.y     dist       Date
#78  78  1994_8_19_0 199419 19 0.3700098 2.230531 49133 28.8 0.3176499 2.104727 824.8680 1994-08-19
#79  79  1994_8_19_6 199419 19 0.3787364 2.214823 49134 28.8 0.3176499 2.104727 765.4631 1994-08-19
#80  80 1994_8_19_12 199419 19 0.3857178 2.200860 49135 28.8 0.3176499 2.104727 720.0335 1994-08-19
#81  81 1994_8_19_18 199419 19 0.3926991 2.190388 49136 28.8 0.3176499 2.104727 700.1729 1994-08-19

which is same as the one in the csv data 与csv数据中的相同

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM