I am trying to get the daily sum from a csv file using the aggregate function but I am encountering the following errors:
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
). The option would be to specify the NA strings within na.strings
to be read as NA
dat <- read.csv(file, header = TRUE, stringsAsFactors = FALSE,
na.strings = " NA", strip.white = TRUE)
After doing the OP's transformation/replacement,
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.