Reputation: 63
My goal is to plot a map with each point representing the year of the highest measured value. So for that I need the year as one value and the Station Name as Row Name.
I get to the point where I get the year of the maximum value for each Station but don´t know how to get the station name as Row Name.
My example is the following:
set.seed(123)
df1<-data.frame(replicate(6,sample(0:200,2500,rep=TRUE)))
date_df1<-seq(as.Date("1995-01-01"), by = "day", length.out = 2500)
test_sto<-cbind(date_df1, df1)
test_sto$date_df1<-as.Date(test_sto$date_df1)
test_sto<-test_sto%>% dplyr::mutate( year = lubridate::year(date_df1),
month = lubridate::month(date_df1),
day = lubridate::day(date_df1))
This is my Dataframe, i then applied the following steps:
To get all values above the treshold for each year and station:
test_year<-aggregate.data.frame(x=test_sto[2:7] > 120, by = list(test_sto$year), FUN = sum, na.rm=TRUE )
This works as it should, the nex is the following
m <- ncol(test_year)
Value <- rep(NA,m)
for (j in 2:m) {
idx<- which.max(test_year[,j])
Value[j] <- test_year[,1][idx]
}
test_test<-Value[2:m]
At the end of this, I get the following table:
x | |
---|---|
1 | 1996 |
2 | 1996 |
3 | 1998 |
4 | 1996 |
5 | 1999 |
6 | 1999 |
But instead of the 1,2,3,4,5..I need there my Column Names (X1,X2,X3 etc.):
x | |
---|---|
X1 | 1996 |
X2 | 1996 |
X3 | 1998 |
X4 | 1996 |
X5 | 1999 |
X6 | 1999 |
but this is the point where i´m struggeling. I tried it with the following step:
test_year$max<-apply(test_year[2:7], 1, FUN = max)
apply(test_year[2:7], 2, FUN = max)
test_year2<-subset(test_year, ncol(2:7) == max(ncol(2:7)))
But i´m just getting an error message saying:
in max(ncol(2:7)): non not-missing Argument for max; give -Inf back<
Maybe someone knows a work around! Thanks in advance!
Upvotes: 1
Views: 165
Reputation: 887851
The 'test_test' is just a vector
. Its magnitude characterized by length
and is a one 1 dimensional object which doesn't have row.names
attribute. But, we can have names
attribute
names(test_test) <- colnames(test_year)[-1]
Upvotes: 2