Finding regional annual maximum values in R - r

I am working with globally gridded data of annual maximum precipitation. However, I want to isolate those maximum value for land areas "only" for each of my 145 years by using a mask (so 145 maximum values based on all land areas). That said, I am receiving only NA values when I apply the mask, and I cannot understand why (when the mask is not applied, the below procedure works just fine). Here is what I have done so far:
Model66 <- brick("MaxPrecNOAA-GFDLGFDL-ESM2Ghistorical.nc", var="onedaymax")
#Applying the mask to isolate land areas only:
data("wrld_simpl")
b <- wrld_simpl
land <- mask(Model66,b)
#To derive highest maximum value for each layer/year for land only (145 years = 145 maximum values)
Gmax <- sapply(unstack(land), function(r){max(values(r))})
Gmax
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
NA NA NA NA NA NA NA
[40] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
NA NA NA NA NA NA NA
[79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
NA NA NA NA NA NA NA
[118] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Why would this be happening? I isolated land only, and my plots correctly show that the mask worked, as only land has values on the plots for each layer/year (and the idea would be take the highest value among these for each layer/year, as I attempted to do with object "Gmax"). Again, when a mask is not applied, NAs don't show up, so I wonder if it is just a small detail causing this when using the mask?
Any help with this would be greatly appreciated!
Thanks!

Try with:
Gmax <- sapply(unstack(land), function(r){max(values(r), na.rm=T)})
Your NAs are considered by R like the maximum value (positive infinitum), you can disable that option with na.rm=TRUE

Related

ifelse function in R to create a new variable [duplicate]

This question already has answers here:
How can I assign a value using if-else conditions in R
(2 answers)
Closed 3 years ago.
I created a new variable "house_group" in my dataset filenamed "adoption". I want entries in "house_group" to be 0 or 1 based on a condition: If education (another variable in the dataset) is 1, house_group should be 1. But if education is 2, house_group should be 0. I used following ifelse function. But it returns NA for the new variable house_group. The options in variable "education" are 1 and 2, and they are categorical not continuous. I want House_group options 1 and 0 as categorical. Any help?
adoption$house_group<-NA
ifelse(adoption$education=="1",adoption$house_group=="1", adoption$house_group=="0")
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[32] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[63] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[94] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[125] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[156] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[187] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[218] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[249] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[280] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[311] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[342] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[373] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[404] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[435] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[466] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[497] NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Here's one way to solve this using data.frame masking. Selecting the correct rows and column you want and then replacing those NA's in groups.
df <- as.data.frame(sample(1:2,10,replace=TRUE))
colnames(df) <- c('education')
df$house_group <- NA
df[df$education == 1,'house_group'] <- 1
df[df$education == 2,'house_group'] <- 0
Another way using your ifelse logic. The problem being that you aren't using the assignment operator "<-" in your ifelse function above.
df$house_group <- ifelse(df$education=="1", 1, 0)

Why when I run robust standard errors I get NA values for t-scores, standard errors, etc

I am working with the following data in Rstudio.
I run a regression minreg <- lm(lwage76~ed76 + exp76 + exp762, data = nlsdata) and then look at the coefficients coeftest(minreg, vcovHC). Up to this point every thing is fine. Then I run the same regression but including an extra variable: minreg_a <- lm(lwage76~ed76 + exp76 + exp762 + kww, data = nlsdata) Then to look at the coefficients coeftest(minreg_a, vcovHC)
t test of coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 4.6051063 NA NA NA
ed76 0.0596900 NA NA NA
exp76 0.0699201 NA NA NA
exp762 -0.0021611 NA NA NA
kww11 0.3504745 NA NA NA
kww12 0.0468874 NA NA NA
kww13 0.2146929 NA NA NA
kww14 0.0623738 NA NA NA
kww15 0.0298164 NA NA NA
kww16 0.2308240 NA NA NA
kww17 0.1766641 NA NA NA
kww18 0.2579742 NA NA NA
kww19 0.2125317 NA NA NA
kww20 0.2498308 NA NA NA
kww21 0.2670052 NA NA NA
kww22 0.3581900 NA NA NA
kww23 0.5047055 NA NA NA
kww24 0.2953582 NA NA NA
kww25 0.3738028 NA NA NA
kww26 0.3819417 NA NA NA
kww27 0.3533177 NA NA NA
kww28 0.4772736 NA NA NA
kww29 0.4024529 NA NA NA
kww30 0.3988244 NA NA NA
kww31 0.4426652 NA NA NA
kww32 0.4117452 NA NA NA
kww33 0.4294092 NA NA NA
kww34 0.4356410 NA NA NA
kww35 0.4399743 NA NA NA
kww36 0.4630381 NA NA NA
kww37 0.4779400 NA NA NA
kww38 0.4867528 NA NA NA
kww39 0.5439840 NA NA NA
kww4 0.1968018 NA NA NA
kww40 0.5427968 NA NA NA
kww41 0.5436628 NA NA NA
kww42 0.6319893 NA NA NA
kww43 0.5522148 NA NA NA
kww44 0.5540705 NA NA NA
kww45 0.5897991 NA NA NA
kww46 0.5372961 NA NA NA
kww47 0.7583224 NA NA NA
kww48 0.8191181 NA NA NA
kww49 0.5448992 NA NA NA
kww50 0.7070670 NA NA NA
kww51 0.6892674 NA NA NA
kww52 0.6381098 NA NA NA
kww53 0.5876115 NA NA NA
kww54 0.7680939 NA NA NA
kww55 1.1111694 NA NA NA
kww56 0.5049158 NA NA NA
kww6 0.0831418 NA NA NA
kww8 0.3058253 NA NA NA
kwwNA 0.3973854 NA NA NA
I have one question here: why the NA outputs; these only occur when I try to run robust standard errors?
This has totally got me boggled
Sorry, you have probably come across the answer by now, but I just came across the same problem with a stratified analysis that I performed. On the entire dataset I could compute robust standard errors with HC0 to HC5, but when stratifying by a relatively small subset (~10% of the sample, n~2300) I could only compute robust SEs with HC0 and HC1 (ie. I got NAs for HC2 and above, just as you did). The problem (I assume) had to do with the co-variance between two variables in my model, ethnicity and income (both factors). Within this subset, many people in minority ethnicities only belonged to a couple levels of the income variable, and vice-versa. When I removed income or ethnicity, or adjusted my stratification so that this subset was twice the size, everything worked (ie. no NAs).
I realize this is a very anecdotal answer, but I hope it helps. If this makes sense to someone with a better understanding of these procedures, perhaps they can provide a more comprehensive response.

How to subset a raster by cell number in R?

I'm trying to subset a raster based on cell numbers. I want to provide a vector of cell numbers and return a raster with the original cell values for those cells referenced in the cell numbers vector. I tried the rasterFromCells() function but this seems to interpolate between cell numbers and doesn't return values, but rather cell numbers. I've tried:
#original raster loaded with 400 sample values ranging from 1:24
foo <- raster(ncol=20, nrow=20)
foo[] <- sample(seq(1,24),400,replace = TRUE)
#vector of desired cell numbers
my.pts <- c(2,20,200)
#rasterFromCells attempt
bar<-rasterFromCells(foo, my.pts, values=TRUE)
How can I return a raster layer with foo's values for cell numbers 2, 20 and 200 and all other cells asNA?
If you want to create a new raster with the values at only the cell locations in my.pts replaced by the values at those cell locations in foo and all other cell values set to NA, you just have to:
create a raster (i.e., bar) the same size as foo.
fill it with NAs
Use bar[my.pts] <- foo[my.pts]
For example:
library(raster)
set.seed(123) ## for reproducible results
foo <- raster(ncols=20, nrows=20)
foo[] <- sample(seq(1,24),400,replace = TRUE)
#vector of desired cell numbers
my.pts <- c(2,20,200)
## create raster the same size as foo filled with NAs
bar <- raster(ncols=ncol(foo), nrows=nrow(foo))
bar[] <- NA
## replace the values with those in foo
bar[my.pts] <- foo[my.pts]
foo[my.pts]
##[1] 19 23 14
bar[]
## [1] NA 19 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 23 NA NA NA NA NA NA NA NA NA NA NA
## [32] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
## [63] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
## [94] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[125] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[156] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[187] NA NA NA NA NA NA NA NA NA NA NA NA NA 14 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[218] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[249] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[280] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[311] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[342] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
##[373] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Another approach to accomplish the same result is to copy foo to bar and then set all cells locations not in my.pts to NAs:
bar <- foo
bar[setdiff(1:ncell(foo),my.pts)] <- NA
The advantage of rasterFromCells is that it returns a smaller raster, as it contains only the cropped version of what you want.
So what you need to do is to feed again the value of your initial raster (r) in the new one (r2), which is eased by the fact that the new one (r2) returns the original cell numbers:
r <- raster(ncols=100, nrows=100)
r[] <- rnorm(ncell(r))
cells <- c(3:5, 210)
r2 <- rasterFromCells(r, cells, values=TRUE)
ini_cells <- getValues(r2)
Simply feed the values according to the index:
r2[] <- r[ini_cells]
This results in a raster of 24 cells instead of 10'000!
c(ncell(r), ncell(r2))
Let us compare the results:
data.frame(Orig=getValues(r)[cells], New=getValues(r2)[ini_cells %in% cells])
[,1] [,2]
[1,] -0.5081512 -0.5081512
[2,] -0.8799739 -0.8799739
[3,] 0.3722788 0.3722788
[4,] -0.7661364 -0.7661364
Note: you wanted to set all others to NA. You would do this with:
r2[!ini_cells %in% cells] <- NA
head(getValues(r2))
-0.5081512 -0.8799739 0.3722788 NA NA NA

Conversion of Data Class from "Factor" to "TS" class

I am trying to plot stock price (Time Series) for PNB (Nifty Index) over a period of 1 year in order to study the patterns. Attached is the data for stock Price in CSV format.
But when I am trying to convert the class of this data from CSV file using zoo (xts) package,
Note: xts is subset of zoo package.
d<-xts(f$Close.Price,order.by=as.Date(f$Date),format="%m/%d/%y")
Error in charToDate(x) :
character string is not in a standard unambiguous format
where f is the dataframe which is the reading the .csv file
I have also tried with date variable with the following command and gives me below error,
s<-as.Date(f$Date, format = "%d/%m/%Y")
s
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[29] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[57] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[85] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[113] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[141] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[169] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[197] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[225] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[253] NA
I am getting NA for the dates.
In other words, I am not able to convert the class of f$Date into "ts" class.
Please help me to convert the data into the correct format.
Try doing it in two steps, using lubridate:
library(lubridate)
df <- read.csv("stockdata.csv", header = T, stringsAsFactors = F)
df$timedata <- mdy(df$timedata)
mdy() will take a 'vector of suspected dates'. You can specify the arrangement of dates with ymd(), mdy(), dmy(), and more. Look up the documentation for lubridate for more.
Hope this helps.

R is unexpectedly transforming field from CSV file to NA

I'm trying to parse CSV file in R. Here is the first line of CSV file with separator ~. Please note i literal at second field position.
2015-10-29 18:49:42~i~186.37.108.44~Mozilla/5.0 (Linux; Android 4.1.2; GT-S6810E Build/JZO54K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.94 Mobile Safari/537.36~ea01627ed45116787d3b1c0224a44d77~?~CL~1443~219~729~335~3155~9214~5
Here is how I'm trying to parse it:
> parsed <- read.csv('i.csv', header=F, sep='~')
> parsed$V2
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[37] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[73] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[109] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[145] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[181] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[217] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[253] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[289] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> table(count.fields('i.csv', sep='~'))
14
310
Why this happens? Why field#2 is NA istead of i? All other fields are ok, field#1 and field#3 do not contains i literal. All other fields are also OK.
> df$V1[1]
[1] 2015-10-29 18:38:04
257 Levels: 2015-10-29 18:38:04 2015-10-29 18:38:07 2015-10-29 18:38:12 ... 2015-10-29 18:51:46
> df$V3[1]
[1] 24.237.158.3
270 Levels: 1.144.97.1 1.187.195.221 1.187.204.84 1.39.12.184 1.39.13.227 1.39.137.12 1.39.33.86 ... 97.44.1.207
For the sake of completion, I'm adding my comment as answer.
Almost all the read functions in R (read.csv, read.csv2, data, read.fwf, unzip, read.delim) call read.table function internally.
And read.table calls type.convert to recycle colClasses if it weren't provided with the function call.
From type.convert at R docs, it says
This is principally a helper function for read.table. Given a character vector, it attempts to convert it to logical, integer, numeric or complex, and failing that converts it to factor unless as.is = TRUE. The first type that can accept all the non-missing values is chosen.
So, type.convert checks if the value is logical, integer, real or complex, in this specific order and if all these options are ruled out, converts value to factor (or character if as.is=T).
In R-3.2.1, (buggy) implementation of strtoc and possibly typeconvert resulted in conversion of i to NA. strtoc has been corrected in R-3.3.0.
In R-3.3.0, type.convert('n±ki') return complex only if k ≠ 1.
From Changes in R-3.3.0:
type.convert("i") now returns a factor instead of a complex value with zero real part and missing imaginary part.

Resources