Dates instead of number of hours on the X-axis?
Ive tried to add dates instead of number of hours on the X-axis on this plot, which represents daily prices at different hours throughout the period of a month.
elspot_prices_2021_hourly_eur <- read_excel("elspot-prices_2021_hourly_eur.xlsx")
elspot_prices_2021_daily_eur <- read_excel("elspot-prices_2021_daily_eur.xlsx")
#Seasonaity of same hour
elspot <- as.double(elspot_prices_2021_hourly_eur$...9[-1]) #DK1 is row 9
plot((24*(1:31) - 21), elspot[(24*(1:31) - 21)], col="deepskyblue",
ylim=c(9, 120), xlab="Hour", ylab="Price in Eur/h",
main="Seasonality of hourly prices in January 2021")
lines((24*(1:31) - 21), elspot[(24*(1:31) - 21)], col="deepskyblue")
points((24*(1:31) - 6), elspot[(24*(1:31) - 6)], col="lightcoral")
lines((24*(1:31) - 6), elspot[(24*(1:31) - 6)], col="lightcoral")
legend("topleft", legend=c("3AM", "6AM"), col=6:3, pch=19, bty="n")
The best I could come up with is
date_daily <- as.Date(elspot_prices_2021_daily_eur$`Elspot Prices in EUR/MWh`,
format="%m/%d/%y %H")[-1]
hours <- c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24")
date_hourly <- paste(hours[(0:8759) %% 24 + 1], date_daily[(0:8759) %/% 24 + 1])
date_hourly <- as_datetime(date_hourly, format="%H %Y-%m-%d")
But without luck
do you know?
how many words do you know
See also questions close to this topic
-
pivot_wider does not keep all the variables
I would like to keep the variable
cat
(category) in the output of my function. However, I am not able to keep it. The idea is to apply a similar function tom <- 1 - (1 - se * p2)^df$n
based on the category. But in order to perform that step, I need to keep the variable category.Here's the code:
#script3 suppressPackageStartupMessages({ library(mc2d) library(tidyverse) }) sim_one <- function() { df<-data.frame(id=c(1:30),cat=c(rep("a",12),rep("b",18)),month=c(1:6,1,6,4,1,5,2,3,2,5,4,6,3:6,4:6,1:5,5),n=rpois(30,5)) nr <- nrow(df) df$n[df$n == "0"] <- 3 se <- rbeta(nr, 96, 6) epi.a <- rpert(nr, min = 1.5, mode = 2, max = 3) p <- 0.2 p2 <- epi.a*p m <- 1 - (1 - se * p2)^df$n results <- data.frame(month = df$month, m, df$cat) results %>% arrange(month) %>% group_by(month) %>% mutate(n = row_number(), .groups = "drop") %>% pivot_wider( id_cols = n, names_from = month, names_glue = "m_{.name}", values_from =m ) } set.seed(99) iters <- 1000 sim_list <- replicate(iters, sim_one(), simplify = FALSE) sim_list[[1]] #> # A tibble: 7 x 7 #> n m_1 m_2 m_3 m_4 m_5 m_6 #> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 1 0.970 0.623 0.905 0.998 0.929 0.980 #> 2 2 0.912 0.892 0.736 0.830 0.890 0.862 #> 3 3 0.795 0.932 0.553 0.958 0.931 0.798 #> 4 4 0.950 0.892 0.732 0.649 0.777 0.743 #> 5 5 NA NA NA 0.657 0.980 0.945 #> 6 6 NA NA NA 0.976 0.836 NA #> 7 7 NA NA NA NA 0.740 NA
Created on 2022-05-07 by the reprex package (v2.0.1)
-
calculate weighted average over several columns with NA
I have a data frame like this one:
ID duration1 duration2 total_duration quantity1 quantity2 1 5 2 7 3 1 2 NA 4 4 3 4 3 5 NA 5 2 NA
I would like to do a weighted mean for each subject like this:
df$weighted_mean<- ((df$duration1*df$quantity1) + (df$duration2*df$quantity2) ) / (df$total_duration)
But as I have NA, this command does not work and it is not very nice....
The result would be this:
ID duration1 duration2 total_duration quantity1 quantity2 weighted_mean 1 5 2 7 3 1 2.43 2 NA 4 4 3 4 4 3 5 NA 5 2 NA 2
Thanks in advance for the help
-
I am to extract data from netCDF file using R for specific loaction the code i've written as showen and I have an error at the end of the code
I need some help with extracting date from NetCDF files using R , I downloaded them from cordex (The Coordinated Regional climate Downscaling Experiment). In total I have some files. This files have dimensions of (longitude, latitude, time) and the variable is maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time. In total I have some files. This files have dimensions of (longitude, latitude, time) and variable maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time.I wrote the code using R but at the end of code, an error appeared. Error ( location subscript out of bounds)
getwd() setwd("C:/Users/20120/climate change/rcp4.5/tasmax")
dir() library ("ncdf4") libra,-ry(ncdf4.helpers) library ("chron") ncin <- nc_open("tasmax_AFR-44_ICHEC-EC-EARTH_rcp45_r1i1p1_KNMI-RACMO22T_v1_mon_200601-201012.nc") lat <- ncvar_get(ncin, "lat") lon <- ncvar_get(ncin, "lon") tori <- ncvar_get(ncin, "time") title <- ncatt_get(ncin,0,"title") institution <- ncatt_get(ncin,0,"institution") datasource <- ncatt_get(ncin,0,"source") references <- ncatt_get(ncin,0,"references") history <- ncatt_get(ncin,0,"history") Conventions <- ncatt_get(ncin,0,"Conventions") tustr <- strsplit(tunits$value,"") ncin$dim$time$units ncin$dim$time$calendar tas_time <- nc.get.time.series(ncin, v = "tasmax", time.dim.name = "time") tas_time[c(1:3, length(tas_time) - 2:0)] tmp.array <- ncvar_get(ncin,"tasmax") dunits <- ncatt_get(ncin,"tasmax","units") tmp.array <- tmp.array-273.15 tunits <- ncatt_get(ncin,"time","units") nc_close(ncin) which.min(abs(lat-28.9)) which.min(abs(lon-30.2)) tmp.slice <- tmp.array[126,32981,] tmp.slice
Error in tmp.array[126, 32981, ] : subscript out of bounds
-
How to convert YYYYMM to YYYY-MM datetime format without day?
I have two datasets that have monthly frequencies. For one of them,
df
, I had to aggregate some data to turn it from daily to monthly using the following code:df_grouped=df.groupby([df.index.to_period('M'),'City ID']).agg({'Estimated Population':'mean','Estimated Population_2019':'mean','Confirmed Rate':['mean','std'],'Death Rate':['mean','std'],'New Confirmed':'sum','New Deaths':'sum'}) df_grouped.index.rename(['Month','City ID'],inplace=True)
After doing these changes my dates became in the format
YYYY-MM
, for example:2020-01 2020-02 ... 2021-07
My other dataset,
df2
, has the date in formatYYYMM
, so I used the following code to convert it:df2['DATE'] = pd.to_datetime(df2['DATE'],format='%Y%m')
My new dates become in the format
YYYY-MM-DD
, where all theDD
become 01, as follows:2020-01-01 2020-02-01 ... 2021-07-01
How can I convert
df2
date now fromYYYY-MM-DD
toYYYY-MM
?I was thinking, maybe there is a way to convert straight from
YYYYMM
toYYYY-MM
? -
convert month of dates into sequence
i want to combine months from years into sequence, for example, i have dataframe like this:
stuff_id date 1 2015-02-03 2 2015-03-03 3 2015-05-19 4 2015-10-13 5 2016-01-07 6 2016-03-20
i want to sequence the months of the date. the desired output is:
stuff_id date month 1 2015-02-03 1 2 2015-03-03 2 3 2015-05-19 4 4 2015-10-13 9 5 2016-01-07 12 6 2016-03-20 14
which means feb'15 is the first month in the date list and jan'2016 is the 12th month after feb'2015
-
PHP | Parse specific german date format to yyyy-mm-dd
Hey I am struggling with a date format . I need to adjust the display of some dates in a wordpress project.
Its not a duplicate of This question I tried the suggestion over there and its not working with that specific date format.
What I have is
german date
in the formatD, d. MM yyyy
looking like this:Fr, 6. Mai 2022
I want to convert it to
yyyy-mm-dd
=2022-05-06
but I cant get it work. I have tried to use date_parse_from_format and date_create_from_format but it seems to fail because of the german month and day names.$date_german = 'Fr, 6. Mai 2022'; $date_english = 'Fri, 6. May 2022'; print_r(date_create_from_format('D, d. F Y', $date_german)); // doesn't work print_r(date_create_from_format('D, d. F Y', $date_english)); // works ()
Another try with IntlDateFormatter
$date = 'Fr, 6. Mai 2022'; $formatter = new IntlDateFormatter("de_DE", IntlDateFormatter::SHORT, IntlDateFormatter::NONE); $formatter->setPattern('D, d. F Y'); $unixtime=$formatter->parse($date); $datetime=new DateTime(); $datetime->setTimestamp($unixtime); echo $datetime->format('Y-m-d');
Not working either, it returns:
1970-01-01
because $unixtime is empty?I also tried to setLocale to de_DE before formatting, but still same problem.
-
r - Plotting monthly time series data in R - cannot plot more than 10 series
I'm having a lot of trouble plotting my time series data in R Studio. My data is laid out as follows:
tsf
Time Series: Start = 1995 End = 2021 Frequency = 1 Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec 1995 10817 8916 9697 10314 9775 7125 9007 6000 4155 3692 2236 996 1996 12773 12562 13479 14280 13839 9168 10959 6582 5162 4815 3768 1946 1997 14691 12982 13545 14131 14162 10415 11420 7870 6340 6869 6777 6637 1998 17192 15480 14703 16903 15921 13381 13779 9127 6676 6511 5419 3447 1999 13578 19470 23411 18190 18979 17296 16588 12561 10405 8537 7304 4003 2000 20100 29419 30125 27147 27832 23874 19728 15847 11477 9301 6933 3486 2001 16528 22258 22146 19027 19436 15688 14558 10609 6799 6563 4816 2480 2002 14724 19424 21391 17215 18775 13017 14385 10044 7649 6598 4497 2766 2003 17051 20182 18564 18484 15365 12180 13313 8859 6830 6371 3781 2012 2004 16875 20084 21150 19057 16153 13619 14144 9599 7390 5830 3763 2033 2005 20002 24153 23160 20864 18331 14950 14149 11086 7475 6290 3779 2134 2006 24605 26384 24858 20634 18951 15048 14905 10749 7259 5479 3074 1509 2007 29281 26495 25974 21427 20232 15465 15738 10006 6674 5301 2857 1304 2008 32961 24290 20190 17587 12172 7369 16175 6822 4364 2699 1174 667 2009 10996 8793 7345 5558 4840 4833 4355 2422 2272 1596 948 474 2010 10469 11707 12379 9599 8893 8314 7018 5310 4683 3742 2146 647 2011 13624 13470 12390 11171 9359 9240 6953 3653 2861 2216 1398 597 2012 14507 10993 10581 9388 7986 5481 6164 3736 2783 2442 1421 774 2013 10735 9671 10596 8113 7095 3293 9306 4504 3257 2832 1307 639 2014 15975 11906 11485 11757 7767 3390 14037 6201 4376 3082 1465 920 2015 20105 15384 17054 13166 9027 3924 21290 8572 5924 3943 1874 847 2016 27106 21173 20096 14847 10125 4143 22462 9781 5842 3831 1846 679 2017 26668 16905 17180 13427 9581 3585 21316 8105 4828 3255 1594 601 2018 25813 16501 16088 11557 9362 3716 20743 7681 4397 2874 1647 778 2019 22279 14178 14404 13794 9126 3858 18741 7202 4104 3214 1676 729 2020 20665 13263 10239 1338 1490 2189 15329 7360 5747 4189 1468 1032 2021 16948 11672 10672 8214 7337 4980 20232 8563 6354 3882 2167 832
When I attempt rudimentary code to plot the data I get the following
plot(tsf) 'Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, : cannot plot more than 10 series as "multiple"'
My data is monthly and therefore 12 months exceed this apparent limit of 10 graphs.I've been able to make some plot by excluding two months but this is not practical for me. I've looked at lots of answers on this, many of which recommending
ggplot() {ggplot2}
The link below had data most closely resembling my data but I still wasn't able to apply it.
issues plotting multivariate time series in R
Any help greatly appreciated.
-
How to plot a Sequential Bayes Factor as participants are added
I am currently analyzing eye-tracking data using the Sequential Bayes Factor method, and I would like to plot how the resulting Bayes Factor (BF; calculated from average looking times) changes as participants are added.
I would like the x-axis to represent the number of participants included in the calculation, and the y-axis to represent the resulting Bayes Factor.
For example, when participants 1-10 are included, BF = [y-value], and that is one plot point on the graph. When participants 1-11 are included, BF = [y-value], and that is the second plot point on the graph.
Is there a way to do this in R?
For example, I have this data set:
ID avg_PTL <chr> <dbl> 1 D07 -0.0609 2 D08 0.0427 3 D12 0.112 4 D15 -0.106 5 D16 0.199 6 D19 0.0677 7 D20 0.0459 8 d21 -0.158 9 D23 0.0650 10 D25 0.0579 11 D27 0.0463 12 D29 0.00822 13 D30 0.00613 14 D36 -0.0484 15 D37 0.0312 16 D39 0.000547 17 D44 0.0336 18 D46 0.0514 19 D48 0.236 20 D51 -0.000487 21 D60 0.0410 22 D61 0.0622 23 D62 0.0337 24 D64 -0.125 25 D65 0.215 26 D66 0.200
And I calculate the BF with:
bf.mono.correct = ttestBF(x = avg_PTL_mono_correct$avg_PTL)
Any tips are much appreciated!
-
Julia plot hline! doesn't work with multiple threads
I have a simple simulation and I want to plot errors on 3 distinct figures. To speed things up I wanted to introduce a little bit of parallel computing.
Threads.@threads for i in 1:3 plt = plot(t, err[:, i], linecolor=:blue, label=[""], linewidth=3) hline!(plt, [0], linestyle=:dash, linecolor=:black, label=[""]) xlabel!(L"t") ylabel!(L"e_%$i") savefig(plt, "fig/Staubli_Slotine_Li$i.pdf") end
Everything stops working when I try running julia with
-t3
flagERROR: LoadError: TaskFailedException Stacktrace: [1] wait @ ./task.jl:334 [inlined] [2] threading_run(func::Function) @ Base.Threads ./threadingconstructs.jl:38 [3] top-level scope @ ./threadingconstructs.jl:97 nested task error: KeyError: key :annotations not found Stacktrace: [1] pop!(h::Dict{Symbol, Any}, key::Symbol) @ Base ./dict.jl:587 [2] pop_kw!(dd::RecipesPipeline.DefaultsDict, k::Symbol) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/utils.jl:57 [3] _update_subplot_args(plt::Plots.Plot{Plots.PGFPlotsXBackend}, sp::Plots.Subplot{Plots.PGFPlotsXBackend}, plotattributes_in::Dict{Symbol, Any}, subplot_index::Int64, remove_pair::Bool) @ Plots ~/.julia/packages/Plots/nzdhU/src/args.jl:2058 [4] _subplot_setup(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:277 [5] plot_setup!(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:138 [6] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/RecipesPipeline.jl:87 [7] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:208 [8] plot!(::Plots.Plot; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:198 [9] plot!(; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:188 [10] #xlabel!#484 @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [11] xlabel! @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [12] macro expansion @ ~/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:29 [inlined] [13] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})(onethread::Bool) @ Main ./threadingconstructs.jl:85 [14] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})() @ Main ./threadingconstructs.jl:52 in expression starting at /home/jcebulsk/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:26
If I comment out
hline!
the script runs without any issue.It looks like I can't have both
hline
and parallel operation.