R error in plot.window(...) need finite 'xlim' values
But I couldn't really do
y = as.numeric(CO2.data$V2)
because then every value was NA.
Well plot
essentially has the same problem.
When reading in data, the first step should always be to put the data into an appropriate format, and only then process to the next step. Your workflow should always look like this, with virtually no exceptions.
In your case, you need to convert the datetime and the numeric values explicitly because R cannot handle the format conversion automatically:
x = strptime(CO2.data$V1, '%d.%m.%Y %H:%M:%S')
y = as.numeric(sub(',', '.', CO2.data$V2))
In particular, you need to specify the date format (first line) and you need to convert decimal commas into decimal points before converting the strings to numbers.
If you use read.csv2
instead of read.table
, you can specify the decimal separator; this allows you to omit the second conversion above:
CO2.data = read.csv2("962RecordedDataCO2.txt", sep=";", dec = ",", stringsAsFactors=FALSE)
Oh, and use FALSE
and TRUE
, not F
and T
— the latter are variables, so some code could redefine the meaning of F
and T
.
Error in plot.window(…): need finite 'xlim' values but it seems all fine
The problem is that the delimiter in the file is a semi-colon rather than a comma. You should have used:
redWineData <- read.delim('winequality-red.csv') # European styled .csv
Then the dataframe would have a column named quality
. At the moment you have a single column named: "X.fixedAcidity.volatileAcidity.citricAcid.residualSugar.chlorides.freeSulfur.dioxide.total.sulfur.dioxide.density.pH.sulphates.alcohol.quality"
Error in plot.window(...) : need finite 'xlim' values in plot
Convert your character to a factor and you can do it.
input$TESTCELL_CONTENT = factor(input$TESTCELL_CONTENT)
Same applies if this is a data frame rather than a "tibble".
R plot - need finite xlim values but all x are finite with no NA's
User @zx8754 marked this question as a duplicate of this question and of this question.
The problem here is that var1
is of class "character"
, like in the questions believed to be duplicates, but it is obvious from its contents that what is needed is a year/quarter
object.
Package zoo
has a function ideal for this, as.yearqtr
.
yq <- zoo::as.yearqtr(df1$var1)
plot(yq, df1$var2, type = "l", col = "red")
Data in dput
format.
df1 <-
structure(list(var1 = c("2012Q1", "2012Q2", "2012Q3", "2012Q4",
"2013Q1", "2013Q2", "2013Q3", "2013Q4", "2014Q1", "2014Q2", "2014Q3",
"2014Q4", "2015Q1", "2015Q2", "2015Q3", "2015Q4", "2016Q1", "2016Q2",
"2016Q3", "2016Q4", "2017Q1", "2017Q2", "2017Q3", "2017Q4", "2018Q1",
"2018Q2", "2018Q3", "2018Q4", "2019Q1", "2019Q2"), var2 = c(NA,
NA, NA, NA, 444618.3, 1556125.2, 744145.1, 844862.2, 773188.2,
1204732.2, 1832308.2, 1732186.6, 1475089.7, 1238791.2, 772359,
927111.5, 982978.9, 581415.1, 489457.8, 446419, 403841, 654630.9,
753729.4, 513755, 587031.5, 465808.7, 462710.4, 537923.9, 409037.8,
785118.7)), class = "data.frame", row.names = c(NA, -30L))
Error in plot.window(...) : need finite 'ylim' values to generate graph in R
When there are only NA
elements, and if we use range/min/max
with na.rm = TRUE
, it returns Inf
> min(NA, na.rm = TRUE)
[1] Inf
Warning message:
In min(NA, na.rm = TRUE) : no non-missing arguments to min; returning Inf
> max(NA, na.rm = TRUE)
[1] -Inf
Warning message:
In max(NA, na.rm = TRUE) : no non-missing arguments to max; returning -Inf
> range(NA, na.rm = TRUE)
[1] Inf -Inf
Warning messages:
1: In min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
2: In max(x, na.rm = na.rm) :
no non-missing arguments to max; returning -Inf
One option is to return 0 if it is NA
...
maxrange <- range(min(0, datas$Numbers, na.rm = TRUE), na.rm = TRUE)
...
-full code
f1 <- function(dmda, CategoryChosse) {
x<-df1 %>% select(starts_with("DR0"))
x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
med<-PV %>%
group_by(Category,Week) %>%
summarize(across(ends_with("PV"), median))
SPV<-df1%>%
inner_join(med, by = c('Category', 'Week')) %>%
mutate(across(matches("^DR0\\d+$"), ~.x +
get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(date1:Category, DR01_DR01_PV:last_col())
SPV<-data.frame(SPV)
mat1 <- df1 %>%
filter(date2 == dmda, Category == CategoryChosse) %>%
select(starts_with("DR0")) %>%
pivot_longer(cols = everything()) %>%
arrange(desc(row_number())) %>%
mutate(cs = cumsum(value)) %>%
filter(cs == 0) %>%
pull(name)
(dropnames <- paste0(mat1,"_",mat1, "_PV"))
SPV <- SPV %>%
filter(date2 == dmda, Category == CategoryChosse) %>%
select(-any_of(dropnames))
if(length(grep("DR0", names(SPV))) == 0) {
SPV[mat1] <- NA_real_
}
datas <-SPV %>%
filter(date2 == ymd(dmda)) %>%
group_by(Category) %>%
summarize(across(starts_with("DR0"), sum)) %>%
pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>%
mutate(name = readr::parse_number(name))
colnames(datas)[-1]<-c("Days","Numbers")
datas <- datas %>%
group_by(Category) %>%
slice((as.Date(dmda) - min(as.Date(df1$date1) [
df1$Category == first(Category)])):max(Days)+1) %>%
ungroup
m<-df1 %>%
group_by(Category,Week) %>%
summarize(across(starts_with("DR1"), mean))
m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
maxrange <- range(min(0, datas$Numbers, na.rm = TRUE), na.rm = TRUE)
maxrange[2] <- maxrange[2] - (maxrange[2] %%10) + 35
max<-max(datas$Days, na.rm = TRUE)+1
plot(Numbers ~ Days, xlim= c(0,max), ylim= c(0,maxrange[2]),
xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
if (nrow(datas)<=2){
abline(h=m,lwd=2)
points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
text(.1,m+ .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")}
else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){
yz <- unique(datas$Numbers)
lines(c(0,datas$Days), c(yz, datas$Numbers), lwd = 2)
points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
text(.1,yz+ .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")}
else{
mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
new.data <- rbind(0, new.data)
lines(new.data$Days,predict(mod,newdata = new.data),lwd=2)
coef<-coef(mod)[2]
points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
}
}
-testing
f1("2021-07-02", "ABC")
Related Topics
Calculate Cumsum() While Ignoring Na Values
Pass Function Arguments to Both Dplyr and Ggplot
Why Is Using '<<-' Frowned Upon and How to Avoid It
Embedded Nul in String' Error When Importing CSV with Fread
Plot One Numeric Variable Against N Numeric Variables in N Plots
Filling Area Under Curve Based on Value
Display Weighted Mean by Group in the Data.Frame
R - How to Get Row & Column Subscripts of Matched Elements from a Distance Matrix
Finding Out Which Functions Are Called Within a Given Function
R Function with No Return Value
Forward and Backward Fill Data Frame in R
Showing String in Formula and Not as Variable in Lm Fit
How to Fix Corrupted Dates in R
What Are the Differences Between Community Detection Algorithms in Igraph
Ggplot2 Plot Without Axes, Legends, etc
Get X-Value Given Y-Value: General Root Finding for Linear/Non-Linear Interpolation Function