Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Bert Gunter
Well, if you know the column subscripts you need, just forget about the names!

I would just write a (one-liner) function to do it for any data frame:

myfun <- function(dat)tapply(dat[,3], dat[,1:2], sum)
## dat[,1:2] is a list because it's a data frame and all data frames are lists

myfun(data_original) ## then gives the result

## you could even make the indices arguments of the myfun if they
change in different
## data sets

-- Bert

On Fri, Oct 21, 2022 at 5:14 PM Kelly Thompson  wrote:
>
> Bert,
> Thanks! I'm pretty sure what you provided gets me to what I was
> looking for, and is much simpler. I really appreciate your help.
>
> A follow-up question:
> I adjusted the code to not use "hard-coded" column names.
>
> mat2 <- with(data_original, tapply( get(names(data_original)[3]),
> list( get(names(data_original)[1]), get(names(data_original)[2])), sum
> ))
>
> Is there any better way to write that?
>
> Thanks again!
> -
>
> For clarity and to improve upon what I previously wrote, and so I can
> practice writing questions like this and asking for help, here's a
> recap of my question and "reproducible code", and the "better way" you
> provided:
>
> I have data presented in a 3-column data frame as shown below in
> "data_original".
>
> I want to aggregate the data in column 3, with the "by" argument using
> the first and second columns of "data_original".
>
> I want the results of the aggregation in a matrix, as shown below in "mat1".
>
> As my end "result", I want a matrix with one row for each unique value
> of column1 of data_original and one column for each unique value of
> column2 of data_original.
>
> What I show below seems like one way this can be done.
>
> My question: Are there easier or better ways to do this, especially in
> Base R, and also in R packages?
>
>
> #create data
> set.seed(1)
> data_original <- data.frame(year = rep(1990:1999, length  = 50),
> category = sample(1:5, size = 50, replace = TRUE),  sales =
> sample(0:9, size = 50 , replace = TRUE) )
> dim(data_original)
>
> #remove rows where data_original[,1] == 1990 & data_original[,2] == 5,
> to ensure there is at least one NA in the desired matrix (this is an
> "edge" case I want the code to "deal with" correctly.)
> data_original <- data_original[ (data_original[,1] == 1990 &
> data_original[,2] == 5) == FALSE, ]
> dim(data_original)
>
> #aggregate data
> data_aggregate_col3_by_col1_and_col2 <- aggregate(x =
> data_original[3], by = list(data_original[,1], data_original[,2]), FUN
> = sum)
> colnames(data_aggregate_col3_by_col1_and_col2) <- colnames(data_original)
> dim(data_aggregate_col3_by_col1_and_col2)
>
> data_expanded <-
> expand.grid(unique(data_aggregate_col3_by_col1_and_col2[,1]),
> unique(data_aggregate_col3_by_col1_and_col2[,2]))
> colnames(data_expanded) <- colnames(data_aggregate_col3_by_col1_and_col2)[1:2]
> dim(data_expanded)
>
> data_expanded <- merge(data_expanded,
> data_aggregate_col3_by_col1_and_col2, all = TRUE)
> dim(data_expanded)
>
> mat1 <- matrix(data = data_expanded[,3], nrow =
> length(unique(data_expanded[,1])), ncol =
> length(unique(data_expanded[,2])) , byrow = TRUE, dimnames = list(
> unique(data_expanded[,1]), unique(data_expanded[,2]) ) )
>
> #this is an easier way, using with and tapply
> mat2 <- with(data_original, tapply( get(names(data_original)[3]),
> list( get(names(data_original)[1]), get(names(data_original)[2])), sum
> ))
> #check that mat1 and mat 2 are "nearly equal"
> all.equal(mat1, mat2)
>
>
>
> Gunter  wrote:
> >
> > "As my end result, I want a matrix or data frame, with one row for each
> > year, and one column for each category."
> >
> > If I understand you correctly, no reshaping gymnastics are needed --
> > just use ?tapply:
> >
> > set.seed(1)
> > do <- data.frame(year = rep(1990:1999, length  = 50),
> > category = sample(1:5, size = 50, replace = TRUE),
> > sales = sample(0:9, size = 50 , replace = TRUE) )
> >
> >
> > with(do, tapply(sales, list(year, category),sum))
> >  ## which gives the matrix:
> >
> >  1  2  3 4 5
> > 1990  13283 NA  55083 87522 64877
> > 1991 NA  80963 NA 30100 28277
> > 1992   9391 202916 NA 55090NA
> > 1993  29696 167344 NANA 17625
> > 1994  98015  99521 NA 70536 52252
> > 1995 157003 NA  26875NA 11366
> > 1996  32986  88683   6562 79475 95282
> > 1997  13601 NA 134757 12398NA
> > 1998  30537  51117  31333 20204NA
> > 1999  39240  87845  62479NA 98804
> >
> > If this is not what you wanted, you may need to explain further or
> > await a response from someone more insightful than I.
> >
> > Cheers,
> > Bert
> >
> >
> > On Fri, Oct 21, 2022 at 3:34 PM Kelly Thompson  wrote:
> > >
> > > As my end result, I want a matrix or data frame, with one row for each
> > > year, and one column for each category.
> > >
> > > On Fri, Oct 21, 2022 at 6:23 PM Kelly Thompson  
> > > wrote:
> > > >
> > > > # I think this might be a better example.
> > > >
> > > > # I have 

Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Kelly Thompson
Bert,
Thanks! I'm pretty sure what you provided gets me to what I was
looking for, and is much simpler. I really appreciate your help.

A follow-up question:
I adjusted the code to not use "hard-coded" column names.

mat2 <- with(data_original, tapply( get(names(data_original)[3]),
list( get(names(data_original)[1]), get(names(data_original)[2])), sum
))

Is there any better way to write that?

Thanks again!
-

For clarity and to improve upon what I previously wrote, and so I can
practice writing questions like this and asking for help, here's a
recap of my question and "reproducible code", and the "better way" you
provided:

I have data presented in a 3-column data frame as shown below in
"data_original".

I want to aggregate the data in column 3, with the "by" argument using
the first and second columns of "data_original".

I want the results of the aggregation in a matrix, as shown below in "mat1".

As my end "result", I want a matrix with one row for each unique value
of column1 of data_original and one column for each unique value of
column2 of data_original.

What I show below seems like one way this can be done.

My question: Are there easier or better ways to do this, especially in
Base R, and also in R packages?


#create data
set.seed(1)
data_original <- data.frame(year = rep(1990:1999, length  = 50),
category = sample(1:5, size = 50, replace = TRUE),  sales =
sample(0:9, size = 50 , replace = TRUE) )
dim(data_original)

#remove rows where data_original[,1] == 1990 & data_original[,2] == 5,
to ensure there is at least one NA in the desired matrix (this is an
"edge" case I want the code to "deal with" correctly.)
data_original <- data_original[ (data_original[,1] == 1990 &
data_original[,2] == 5) == FALSE, ]
dim(data_original)

#aggregate data
data_aggregate_col3_by_col1_and_col2 <- aggregate(x =
data_original[3], by = list(data_original[,1], data_original[,2]), FUN
= sum)
colnames(data_aggregate_col3_by_col1_and_col2) <- colnames(data_original)
dim(data_aggregate_col3_by_col1_and_col2)

data_expanded <-
expand.grid(unique(data_aggregate_col3_by_col1_and_col2[,1]),
unique(data_aggregate_col3_by_col1_and_col2[,2]))
colnames(data_expanded) <- colnames(data_aggregate_col3_by_col1_and_col2)[1:2]
dim(data_expanded)

data_expanded <- merge(data_expanded,
data_aggregate_col3_by_col1_and_col2, all = TRUE)
dim(data_expanded)

mat1 <- matrix(data = data_expanded[,3], nrow =
length(unique(data_expanded[,1])), ncol =
length(unique(data_expanded[,2])) , byrow = TRUE, dimnames = list(
unique(data_expanded[,1]), unique(data_expanded[,2]) ) )

#this is an easier way, using with and tapply
mat2 <- with(data_original, tapply( get(names(data_original)[3]),
list( get(names(data_original)[1]), get(names(data_original)[2])), sum
))
#check that mat1 and mat 2 are "nearly equal"
all.equal(mat1, mat2)



Gunter  wrote:
>
> "As my end result, I want a matrix or data frame, with one row for each
> year, and one column for each category."
>
> If I understand you correctly, no reshaping gymnastics are needed --
> just use ?tapply:
>
> set.seed(1)
> do <- data.frame(year = rep(1990:1999, length  = 50),
> category = sample(1:5, size = 50, replace = TRUE),
> sales = sample(0:9, size = 50 , replace = TRUE) )
>
>
> with(do, tapply(sales, list(year, category),sum))
>  ## which gives the matrix:
>
>  1  2  3 4 5
> 1990  13283 NA  55083 87522 64877
> 1991 NA  80963 NA 30100 28277
> 1992   9391 202916 NA 55090NA
> 1993  29696 167344 NANA 17625
> 1994  98015  99521 NA 70536 52252
> 1995 157003 NA  26875NA 11366
> 1996  32986  88683   6562 79475 95282
> 1997  13601 NA 134757 12398NA
> 1998  30537  51117  31333 20204NA
> 1999  39240  87845  62479NA 98804
>
> If this is not what you wanted, you may need to explain further or
> await a response from someone more insightful than I.
>
> Cheers,
> Bert
>
>
> On Fri, Oct 21, 2022 at 3:34 PM Kelly Thompson  wrote:
> >
> > As my end result, I want a matrix or data frame, with one row for each
> > year, and one column for each category.
> >
> > On Fri, Oct 21, 2022 at 6:23 PM Kelly Thompson  wrote:
> > >
> > > # I think this might be a better example.
> > >
> > > # I have data presented in a "vertical" dataframe as shown below in
> > > data_original.
> > > # I want this data in a matrix or "grid", as shown below.
> > > # What I show below seems like one way this can be done.
> > >
> > > # My question: Are there easier or better ways to do this, especially
> > > in Base R, and also in R packages?
> > >
> > > #create data
> > > set.seed(1)
> > > data_original <- data.frame(year = rep(1990:1999, length  = 50),
> > > category = sample(1:5, size = 50, replace = TRUE),  sales =
> > > sample(0:9, size = 50 , replace = TRUE) )
> > > dim(data_original)
> > >
> > > #remove rows where data_original$year == 1990 & data_original$category
> > > == 5, to ensure there is at least one NA in the "grid"
> > > 

Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Bert Gunter
"As my end result, I want a matrix or data frame, with one row for each
year, and one column for each category."

If I understand you correctly, no reshaping gymnastics are needed --
just use ?tapply:

set.seed(1)
do <- data.frame(year = rep(1990:1999, length  = 50),
category = sample(1:5, size = 50, replace = TRUE),
sales = sample(0:9, size = 50 , replace = TRUE) )


with(do, tapply(sales, list(year, category),sum))
 ## which gives the matrix:

 1  2  3 4 5
1990  13283 NA  55083 87522 64877
1991 NA  80963 NA 30100 28277
1992   9391 202916 NA 55090NA
1993  29696 167344 NANA 17625
1994  98015  99521 NA 70536 52252
1995 157003 NA  26875NA 11366
1996  32986  88683   6562 79475 95282
1997  13601 NA 134757 12398NA
1998  30537  51117  31333 20204NA
1999  39240  87845  62479NA 98804

If this is not what you wanted, you may need to explain further or
await a response from someone more insightful than I.

Cheers,
Bert


On Fri, Oct 21, 2022 at 3:34 PM Kelly Thompson  wrote:
>
> As my end result, I want a matrix or data frame, with one row for each
> year, and one column for each category.
>
> On Fri, Oct 21, 2022 at 6:23 PM Kelly Thompson  wrote:
> >
> > # I think this might be a better example.
> >
> > # I have data presented in a "vertical" dataframe as shown below in
> > data_original.
> > # I want this data in a matrix or "grid", as shown below.
> > # What I show below seems like one way this can be done.
> >
> > # My question: Are there easier or better ways to do this, especially
> > in Base R, and also in R packages?
> >
> > #create data
> > set.seed(1)
> > data_original <- data.frame(year = rep(1990:1999, length  = 50),
> > category = sample(1:5, size = 50, replace = TRUE),  sales =
> > sample(0:9, size = 50 , replace = TRUE) )
> > dim(data_original)
> >
> > #remove rows where data_original$year == 1990 & data_original$category
> > == 5, to ensure there is at least one NA in the "grid"
> > data_original <- data_original[ (data_original$year == 1990 &
> > data_original$category == 5) == FALSE, ]
> > dim(data_original)
> >
> > #aggregate data
> > data_aggregate_sum_by_year_and_category <- aggregate(x =
> > data_original$sales, by = list(year = data_original$year, category =
> > data_original$category), FUN = sum)
> > colnames(data_aggregate_sum_by_year_and_category) <- c('year',
> > 'category', 'sum_of_sales')
> > dim(data_aggregate_sum_by_year_and_category)
> >
> > data_expanded <- expand.grid(year =
> > unique(data_aggregate_sum_by_year_and_category$year), category =
> > unique(data_aggregate_sum_by_year_and_category$category))
> > dim(data_expanded)
> > data_expanded <- merge(data_expanded,
> > data_aggregate_sum_by_year_and_category, all = TRUE)
> > dim(data_expanded)
> >
> > mat <- matrix(data = data_expanded$sum_of_sales, nrow =
> > length(unique(data_expanded$year)), ncol =
> > length(unique(data_expanded$category)) , byrow = TRUE, dimnames =
> > list( unique(data_expanded$year), unique(data_expanded$category) ) )
> >
> >
> > data_original
> > data_expanded
> > mat
> >
> > On Fri, Oct 21, 2022 at 5:03 PM Kelly Thompson  wrote:
> > >
> > > ###
> > > #I have data presented in a "vertical" data frame as shown below in
> > > data_original.
> > > #I want this data in a matrix or "grid", as shown below.
> > > #What I show below seems like one way this can be done.
> > >
> > > #My question: Are there easier or better ways to do this, especially
> > > in Base R, and also in R packages?
> > >
> > > #reproducible example
> > >
> > > data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
> > > size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )
> > >
> > > data_expanded <- expand.grid(unique(data_original$year),
> > > unique(data_original$size), stringsAsFactors = FALSE )
> > > colnames(data_expanded) <- c('year', 'size')
> > > data_expanded <- merge(data_expanded, data_original, all = TRUE)
> > >
> > > mat <- matrix(data = data_expanded $n, nrow =
> > > length(unique(data_expanded $year)), ncol =
> > > length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
> > > unique(data_expanded$year), unique(data_expanded$size) ) )
> > >
> > > data_original
> > > data_expanded
> > > mat
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Kelly Thompson
As my end result, I want a matrix or data frame, with one row for each
year, and one column for each category.

On Fri, Oct 21, 2022 at 6:23 PM Kelly Thompson  wrote:
>
> # I think this might be a better example.
>
> # I have data presented in a "vertical" dataframe as shown below in
> data_original.
> # I want this data in a matrix or "grid", as shown below.
> # What I show below seems like one way this can be done.
>
> # My question: Are there easier or better ways to do this, especially
> in Base R, and also in R packages?
>
> #create data
> set.seed(1)
> data_original <- data.frame(year = rep(1990:1999, length  = 50),
> category = sample(1:5, size = 50, replace = TRUE),  sales =
> sample(0:9, size = 50 , replace = TRUE) )
> dim(data_original)
>
> #remove rows where data_original$year == 1990 & data_original$category
> == 5, to ensure there is at least one NA in the "grid"
> data_original <- data_original[ (data_original$year == 1990 &
> data_original$category == 5) == FALSE, ]
> dim(data_original)
>
> #aggregate data
> data_aggregate_sum_by_year_and_category <- aggregate(x =
> data_original$sales, by = list(year = data_original$year, category =
> data_original$category), FUN = sum)
> colnames(data_aggregate_sum_by_year_and_category) <- c('year',
> 'category', 'sum_of_sales')
> dim(data_aggregate_sum_by_year_and_category)
>
> data_expanded <- expand.grid(year =
> unique(data_aggregate_sum_by_year_and_category$year), category =
> unique(data_aggregate_sum_by_year_and_category$category))
> dim(data_expanded)
> data_expanded <- merge(data_expanded,
> data_aggregate_sum_by_year_and_category, all = TRUE)
> dim(data_expanded)
>
> mat <- matrix(data = data_expanded$sum_of_sales, nrow =
> length(unique(data_expanded$year)), ncol =
> length(unique(data_expanded$category)) , byrow = TRUE, dimnames =
> list( unique(data_expanded$year), unique(data_expanded$category) ) )
>
>
> data_original
> data_expanded
> mat
>
> On Fri, Oct 21, 2022 at 5:03 PM Kelly Thompson  wrote:
> >
> > ###
> > #I have data presented in a "vertical" data frame as shown below in
> > data_original.
> > #I want this data in a matrix or "grid", as shown below.
> > #What I show below seems like one way this can be done.
> >
> > #My question: Are there easier or better ways to do this, especially
> > in Base R, and also in R packages?
> >
> > #reproducible example
> >
> > data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
> > size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )
> >
> > data_expanded <- expand.grid(unique(data_original$year),
> > unique(data_original$size), stringsAsFactors = FALSE )
> > colnames(data_expanded) <- c('year', 'size')
> > data_expanded <- merge(data_expanded, data_original, all = TRUE)
> >
> > mat <- matrix(data = data_expanded $n, nrow =
> > length(unique(data_expanded $year)), ncol =
> > length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
> > unique(data_expanded$year), unique(data_expanded$size) ) )
> >
> > data_original
> > data_expanded
> > mat

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Kelly Thompson
# I think this might be a better example.

# I have data presented in a "vertical" dataframe as shown below in
data_original.
# I want this data in a matrix or "grid", as shown below.
# What I show below seems like one way this can be done.

# My question: Are there easier or better ways to do this, especially
in Base R, and also in R packages?

#create data
set.seed(1)
data_original <- data.frame(year = rep(1990:1999, length  = 50),
category = sample(1:5, size = 50, replace = TRUE),  sales =
sample(0:9, size = 50 , replace = TRUE) )
dim(data_original)

#remove rows where data_original$year == 1990 & data_original$category
== 5, to ensure there is at least one NA in the "grid"
data_original <- data_original[ (data_original$year == 1990 &
data_original$category == 5) == FALSE, ]
dim(data_original)

#aggregate data
data_aggregate_sum_by_year_and_category <- aggregate(x =
data_original$sales, by = list(year = data_original$year, category =
data_original$category), FUN = sum)
colnames(data_aggregate_sum_by_year_and_category) <- c('year',
'category', 'sum_of_sales')
dim(data_aggregate_sum_by_year_and_category)

data_expanded <- expand.grid(year =
unique(data_aggregate_sum_by_year_and_category$year), category =
unique(data_aggregate_sum_by_year_and_category$category))
dim(data_expanded)
data_expanded <- merge(data_expanded,
data_aggregate_sum_by_year_and_category, all = TRUE)
dim(data_expanded)

mat <- matrix(data = data_expanded$sum_of_sales, nrow =
length(unique(data_expanded$year)), ncol =
length(unique(data_expanded$category)) , byrow = TRUE, dimnames =
list( unique(data_expanded$year), unique(data_expanded$category) ) )


data_original
data_expanded
mat

On Fri, Oct 21, 2022 at 5:03 PM Kelly Thompson  wrote:
>
> ###
> #I have data presented in a "vertical" data frame as shown below in
> data_original.
> #I want this data in a matrix or "grid", as shown below.
> #What I show below seems like one way this can be done.
>
> #My question: Are there easier or better ways to do this, especially
> in Base R, and also in R packages?
>
> #reproducible example
>
> data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
> size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )
>
> data_expanded <- expand.grid(unique(data_original$year),
> unique(data_original$size), stringsAsFactors = FALSE )
> colnames(data_expanded) <- c('year', 'size')
> data_expanded <- merge(data_expanded, data_original, all = TRUE)
>
> mat <- matrix(data = data_expanded $n, nrow =
> length(unique(data_expanded $year)), ncol =
> length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
> unique(data_expanded$year), unique(data_expanded$size) ) )
>
> data_original
> data_expanded
> mat

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Jeff Newmiller
Your selection priorities are inverted: ifelse is vectorised... use it to make 
many individual choices at once with a single atomic vector result. If-else is 
a control-flow construct... you can return one object of any type from it based 
on a single comparison or alter variables and ignore the return value (or both, 
though that is probably not going to make for clear readability). Their use 
cases might appear to overlap if you choose to work with a length-one vector, 
but that is a somewhat obscure mis-use of ifelse.

On October 21, 2022 10:38:48 AM PDT, "Ebert,Timothy Aaron"  
wrote:
>Is there a place where you would use ifelse()? I used it here because it was 
>short and there was no indication of lots of data. In the example I cannot 
>tell the difference of a few hundred milliseconds execution time. Benchmarking 
>code is important for larger problems.
>
>Tim
>
>-Original Message-
>From: Martin Maechler  
>Sent: Friday, October 21, 2022 8:43 AM
>To: Ebert,Timothy Aaron 
>Cc: Andrew Simmons ; Jinsong Zhao ; 
>R-help Mailing List 
>Subject: Re: [R] unexpected 'else' in " else"
>
>[External Email]
>
>> Ebert,Timothy Aaron
>> on Fri, 21 Oct 2022 12:05:58 + writes:
>
>> I can get it to work with
>> ifelse(is.matrix(r), r[w!=0, , drop=FALSE], r[w!=0])
>
>Note that this is *not* good advice:
>
>  if(Cnd) A else Bis very much more efficient  than
>  ifelse(Cnd, A, B)
>
>whenever it is appropriate, i.e.,
>the condition Cnd is a simple TRUE or FALSE.
>
>ifelse() is very much over-used!
>
>{For the more sophisticated reader:
> In R, these both are function calls:
> `if` is a function of 3 argument with a "peculiar" syntax and  the third 
> argument with default NULL.
>}
>
>Martin Maechler
>ETH Zurich  and  R Core team
>
>
>
>> With w and r as defined r is not a  matrix, so the first part will never 
> execute. The test is for w not equal to zero so it is always true for these 
> vectors. It is usually good to have test code such that all possible cases 
> are activated.
>
>> r<--1:8
>> w<- -1:5
>> if(is.matrix(r)){
>> r[w!=0, , drop=FALSE]
>> } else r[w != 0]
>
>> I think this also works. The "else" must follow the } and you put in a 
> carriage return after the }
>
>> I think that is the answer, but not 100% sure.
>
>> Tim
>
>> -Original Message-
>> From: R-help  On Behalf Of Andrew Simmons
>> Sent: Friday, October 21, 2022 5:37 AM
>> To: Jinsong Zhao 
>> Cc: R-help Mailing List 
>> Subject: Re: [R] unexpected 'else' in " else"
>
>> [External Email]
>
>> The error comes from the expression not being wrapped with braces. You 
> could change it to
>
>> if (is.matrix(r)) {
>> r[w != 0, , drop = FALSE]
>> } else r[w != 0]
>
>> or
>
>> {
>> if (is.matrix(r))
>> r[w != 0, , drop = FALSE]
>> else r[w != 0]
>> }
>
>> or
>
>> if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]
>
>
>> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:
>
>>> Hi there,
>>>
>>> The following code would cause R error:
>>>
>>> > w <- 1:5
>>> > r <- 1:5
>>> > if (is.matrix(r))
>>> + r[w != 0, , drop = FALSE]
>>> > else r[w != 0]
>>> Error: unexpected 'else' in "else"
>>>
>>> However, the code:
>>> if (is.matrix(r))
>>> r[w != 0, , drop = FALSE]
>>> else r[w != 0]
>>> is extracted from stats::weighted.residuals.
>>>
>>> My question is why the code in the function does not cause error?
>>>
>>> Best,
>>> Jinsong
>>>
>>> __
>>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>>> https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat
>>> .ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl
>>> .edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e
>>> 1b84%7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4w
>>> LjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>>> sdata=9ImIUx0YyKjFMTDRrwa5fnkqiJL9aDjpGCRxxfI6Hlk%3Dreserved
>>> =0
>>> PLEASE do read the posting guide
>>> 
> https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r%2Fdata=05%7C01%7Ctebert%40ufl.edu%7Cd3824be0a76a4e488dda08dab361d1e6%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019529977132811%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=MTmSNg1tfjToCYtWtMf01Hhy93K0TpT3DPwuvYqVv0s%3Dreserved=0
>>> -project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%
>>> 7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%
>>> 7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwM
>>> DAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>>> 

Re: [R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Jeff Newmiller
This operation goes by a variety of names... reshape (stats), cast (reshape2), 
spread (tidyr), and pivot_wider (tidyr).

The stats package reshape function is built-in, but uses terminology that can 
be confusing, and may not come out sorted the way you want so pre-converting to 
factor or post-sorting may be needed. Other packages may be easier to work with.

ans <- reshape(
  data_original
, direction = "wide"
, idvar = "year"
, timevar = "size"
)
ans <- ans[ order( ans$year ), ]
ans

On October 21, 2022 2:03:19 PM PDT, Kelly Thompson  wrote:
>###
>#I have data presented in a "vertical" data frame as shown below in
>data_original.
>#I want this data in a matrix or "grid", as shown below.
>#What I show below seems like one way this can be done.
>
>#My question: Are there easier or better ways to do this, especially
>in Base R, and also in R packages?
>
>#reproducible example
>
>data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
>size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )
>
>data_expanded <- expand.grid(unique(data_original$year),
>unique(data_original$size), stringsAsFactors = FALSE )
>colnames(data_expanded) <- c('year', 'size')
>data_expanded <- merge(data_expanded, data_original, all = TRUE)
>
>mat <- matrix(data = data_expanded $n, nrow =
>length(unique(data_expanded $year)), ncol =
>length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
>unique(data_expanded$year), unique(data_expanded$size) ) )
>
>data_original
>data_expanded
>mat
>
>__
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

-- 
Sent from my phone. Please excuse my brevity.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] getting data from a "vertical" table into a "2-dimensional" grid

2022-10-21 Thread Kelly Thompson
###
#I have data presented in a "vertical" data frame as shown below in
data_original.
#I want this data in a matrix or "grid", as shown below.
#What I show below seems like one way this can be done.

#My question: Are there easier or better ways to do this, especially
in Base R, and also in R packages?

#reproducible example

data_original <- data.frame(year = c('1990', '1999', '1990', '1989'),
size = c('s', 'l', 'xl', 'xs'),  n = c(99, 33, 3, 4) )

data_expanded <- expand.grid(unique(data_original$year),
unique(data_original$size), stringsAsFactors = FALSE )
colnames(data_expanded) <- c('year', 'size')
data_expanded <- merge(data_expanded, data_original, all = TRUE)

mat <- matrix(data = data_expanded $n, nrow =
length(unique(data_expanded $year)), ncol =
length(unique(data_expanded $size)) , byrow = TRUE, dimnames = list(
unique(data_expanded$year), unique(data_expanded$size) ) )

data_original
data_expanded
mat

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Adding page numbers to existing PDFs

2022-10-21 Thread Gabor Grothendieck
Create a pdf using latex that has only page numbers and then
superimpose that with your pdf using the free utility pdftk.  The
animation R package has an interface to pdftk. Google to locate
pdftk and again to locate instructions.

There are also freeware GUI Windows programs  that are easy
to use.  This has nothing to do with R.  The one I have used is
A-PDF Number.

On Fri, Oct 21, 2022 at 1:49 PM Dennis Fisher  wrote:
>
> R 4.2.1
> OS X
>
> Colleagues
>
> I have multipage PDF files that were created in R — the files do NOT have 
> page numbers.  I would like to add page numbers after the fact, i.e., read a 
> file into R, add margin text, then output as a PDF.
> Can this be done in R (base R or a package)?
> It can be done in Python using reportlab.pdfgen — however, the file size 
> increases prohibitively.
>
> Dennis
>
> Dennis Fisher MD
> P < (The "P Less Than" Company)
> Phone / Fax: 1-866-PLessThan (1-866-753-7784)
> www.PLessThan.com
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Adding page numbers to existing PDFs

2022-10-21 Thread J C Nash

It is not automatic, but I've used Xournal for different tasks of editing a pdf.
It would certainly allow page numbers to be added, essentially by overlaying a
text box on each page. Clumsy, but possibly useful.

I tend to use Xournal to blank parts of documents that recipients should not 
see,
e.g., when sending a credit card statement to justify a payment but only 
wanting to
reveal selected lines. Or when adding an image of a signature to a form. Or 
filling in
text on a form.

Truthfully, a tool "addpg2pdf" that did things tidily and automatically could 
be useful.

JN

On 2022-10-21 14:04, Dennis Fisher wrote:

Bert et al.

I searched with slightly different text and found various packages that might 
be relevant:
pdftools
staplr
QPDF

However, as far as I can tell, none of these offers the specific functionality 
that I need.

Dennis

Dennis Fisher MD
P < (The "P Less Than" Company)
Phone / Fax: 1-866-PLessThan (1-866-753-7784)
www.PLessThan.com 





On Oct 21, 2022, at 10:57 AM, Bert Gunter  wrote:

"R packages to edit pdf files



[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] [EXT] Re: Linestring values to vector

2022-10-21 Thread David Stevens
The way I did this recently is to look into the .dbf file that comes 
with the shapefile group from ESRI or your feature site, and search the 
feature names for the one I want. This gives you an index to use to 
search for the feature in the actual shapefile. Then, once the shapefile 
is loaded into R using the shapefiles package, you can get the vectors 
of polygon vertices by

lr <- shapefiles::read.shapefile(myFile) # lr is the shapefile object

sfs <- lr$shp[myIndex] #sfs will be a list and the first element is the 
geometry
sfp <- sfs[[1]]$points #sfp is the set of X and Y vertices

lines(sfp$X],sfp$Y,col='red',lwd=2)

David

David K Stevens, PhD, PE, Professor
Civil and Environmental Engineering
Utah Water Research Laboratory
Utah State University
8200 Old Main Hill
Logan, UT 84322-8200
david.stev...@usu.edu
(435) 797-3229 (office)

On 10/21/2022 12:01 PM, Jeff Newmiller wrote:
> As the Posting Guide would have warned you, you will probably have better 
> luck asking this kind of question on the R-sig-geo mailing list.
>
> On October 21, 2022 10:45:30 AM PDT, Nick Wray  wrote:
>> Hello I have downloaded a large shapefile dataset of UK rivers and I want
>> to isolate (as an ordinary R string) the LINESTRING values for particular
>> lines, corresponding to rivers
>> Looking at the first line I can isolate the geometry by
>>
>> Hello I have downloaded a large shapefile dataset of UK rivers and I want
>> to isolate (as an ordinary R string) the LINESTRING values for particular
>> lines, corresponding to rivers
>>
>> Looking at the first line I can isolate the geometry by
>>
>>
>>
>> st_geometry(rivers[1,8])
>>
>>
>>
>> Geometry set for 1 feature
>> Geometry type: LINESTRING
>> Dimension: XYZ
>> Bounding box:  xmin: 462010.6 ymin: 1213039 xmax: 462306.5 ymax: 1213199
>> z_range:   zmin: 0 zmax: 0
>> Projected CRS: OSGB 1936 / British National Grid
>>
>> LINESTRING Z (462306.5 1213048 0, 462275.4 1213...
>>
>>
>> What I need is all the values in the LINESTRING as a common or garden R
>> vector, but I cannot find a way to do this.
>>
>> Does anyone know how?  Thanks, Nick Wray
>>
>>[[alternative HTML version deleted]]
>>
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> --
> Sent from my phone. Please excuse my brevity.
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> CAUTION: This email originated from outside of USU. If this appears to be a 
> USU employee, beware of impersonators. Do not click links, reply, download 
> images, or open attachments unless you verify the sender’s identity and know 
> the content is safe.
>
__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Adding page numbers to existing PDFs

2022-10-21 Thread Dennis Fisher
Bert et al.

I searched with slightly different text and found various packages that might 
be relevant:
pdftools
staplr
QPDF

However, as far as I can tell, none of these offers the specific functionality 
that I need.

Dennis

Dennis Fisher MD
P < (The "P Less Than" Company)
Phone / Fax: 1-866-PLessThan (1-866-753-7784)
www.PLessThan.com 




> On Oct 21, 2022, at 10:57 AM, Bert Gunter  wrote:
> 
> "R packages to edit pdf files


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] [EXTERNAL] Re: unexpected 'else' in " else"

2022-10-21 Thread Jorgen Harmse via R-help
Thank you. I knew it had nothing to do with the choice of environment, but I 
thought I had seen such unwrapped code working in files in a previous version. 
Maybe I misremembered. Incidentally, there is nothing special about braces: 
anything that makes the statement incomplete will do.

Regards,
Jorgen.


> evalq( if (FALSE)

  cat("This shouldn't happen.\n")

else

  cat("Everything is fine.\n"),

+ .GlobalEnv

+ )

Everything is fine.

> x <- 1:5

> x[ if(FALSE) 1L

+else 2L

+  ]

[1] 2


From: Andrew Simmons 
Date: Friday, 21October, 2022 at 11:20
To: Jorgen Harmse 
Cc: r-help@r-project.org 
Subject: [EXTERNAL] Re: [R] unexpected 'else' in " else"
The code working inside stats::weighted.residuals has nothing to do
with being evaluated in a different environment than globalenv() and
has nothing to do with being inside a package.
The reason the code works inside stats::weighted.residuals is because
the function body is wrapped with braces. You can try it yourself:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("if (TRUE) \n'evaluating cons.expr'\nelse
'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(source(FILE, local = TRUE, echo = TRUE, verbose = FALSE))
})

If you try entering it as a function, it still fails:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("function () \nif (TRUE) \n'evaluating
cons.expr'\nelse 'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(source(FILE, local = TRUE, echo = TRUE, verbose = FALSE))
})

But R packages use sys.source() instead of source() to run R code, but
it still fails if you run it:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("if (TRUE) \n'evaluating cons.expr'\nelse
'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(sys.source(FILE, envir = environment()))
})

The part that matters is that the function body is wrapped with
braces. `if` statements inside braces or parenthesis (or possibly
brackets) will continue looking for `else` even after `cons.expr` and
a newline has been fully parsed, but will not otherwise.

On Fri, Oct 21, 2022 at 10:39 AM Jorgen Harmse via R-help
 wrote:
>
> Andrew Simmons is correct but doesn't explain why the code works in the 
> package. This is one of only two differences I have found between running 
> code at the command line and running it from a file. (The other difference is 
> that code in a file is often executed in an environment other than 
> .GlobalEnv. There is some related sugar around packages that usually makes 
> things work the way a user would want.) At the command line, R executes code 
> whenever RETURN could be interpreted as the end of a statement. "If(�.) �. 
> RETURN" is ambiguous: will it be followed by "else", or is it a complete 
> statement? If it's in a file or wrapped in a block or other structure that 
> obviously hasn't ended yet then R will wait to see the next line of input, 
> but if it could be a complete statement then not executing it would cause a 
> lot of frustration for users. Once the statement is executed, R expects 
> another statement, and no statement begins with "else". (Maybe the 
> interpreter could be enhanced to keep the "if" open under some conditions, 
> but I haven't thought it through. In particular, "if" without "else" is NULL 
> if the condition is FALSE, so it might be necessary to undo an assignment, 
> and that seems very difficult.)
>
> Regards,
> Jorgen Harmse.
>
>
> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:
>
> > Hi there,
> >
> > The following code would cause R error:
> >
> >  > w <- 1:5
> >  > r <- 1:5
> >  > if (is.matrix(r))
> > + r[w != 0, , drop = FALSE]
> >  > else r[w != 0]
> > Error: unexpected 'else' in "else"
> >
> > However, the code:
> >  if (is.matrix(r))
> >  r[w != 0, , drop = FALSE]
> >  else r[w != 0]
> > is extracted from stats::weighted.residuals.
> >
> > My question is why the code in the function does not cause error?
> >
> > Best,
> > Jinsong
> >
> > __
> > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>
> [[alternative HTML version deleted]]
>
>
>
>
> --
>
> Subject: Digest Footer
>
> ___
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide 

Re: [R] Linestring values to vector

2022-10-21 Thread Jeff Newmiller
As the Posting Guide would have warned you, you will probably have better luck 
asking this kind of question on the R-sig-geo mailing list.

On October 21, 2022 10:45:30 AM PDT, Nick Wray  wrote:
>Hello I have downloaded a large shapefile dataset of UK rivers and I want
>to isolate (as an ordinary R string) the LINESTRING values for particular
>lines, corresponding to rivers
>Looking at the first line I can isolate the geometry by
>
>Hello I have downloaded a large shapefile dataset of UK rivers and I want
>to isolate (as an ordinary R string) the LINESTRING values for particular
>lines, corresponding to rivers
>
>Looking at the first line I can isolate the geometry by
>
>
>
>st_geometry(rivers[1,8])
>
>
>
>Geometry set for 1 feature
>Geometry type: LINESTRING
>Dimension: XYZ
>Bounding box:  xmin: 462010.6 ymin: 1213039 xmax: 462306.5 ymax: 1213199
>z_range:   zmin: 0 zmax: 0
>Projected CRS: OSGB 1936 / British National Grid
>
>LINESTRING Z (462306.5 1213048 0, 462275.4 1213...
>
>
>What I need is all the values in the LINESTRING as a common or garden R
>vector, but I cannot find a way to do this.
>
> Does anyone know how?  Thanks, Nick Wray
>
>   [[alternative HTML version deleted]]
>
>__
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

-- 
Sent from my phone. Please excuse my brevity.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Adding page numbers to existing PDFs

2022-10-21 Thread Bert Gunter
Have you done a web search on "R packages to edit pdf files" or similar? I
got what looked like relevant hits with it.

Bert

On Fri, Oct 21, 2022 at 10:49 AM Dennis Fisher  wrote:

> R 4.2.1
> OS X
>
> Colleagues
>
> I have multipage PDF files that were created in R — the files do NOT have
> page numbers.  I would like to add page numbers after the fact, i.e., read
> a file into R, add margin text, then output as a PDF.
> Can this be done in R (base R or a package)?
> It can be done in Python using reportlab.pdfgen — however, the file size
> increases prohibitively.
>
> Dennis
>
> Dennis Fisher MD
> P < (The "P Less Than" Company)
> Phone / Fax: 1-866-PLessThan (1-866-753-7784)
> www.PLessThan.com
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Linestring values to vector

2022-10-21 Thread Nick Wray
Hello I have downloaded a large shapefile dataset of UK rivers and I want
to isolate (as an ordinary R string) the LINESTRING values for particular
lines, corresponding to rivers
Looking at the first line I can isolate the geometry by

Hello I have downloaded a large shapefile dataset of UK rivers and I want
to isolate (as an ordinary R string) the LINESTRING values for particular
lines, corresponding to rivers

Looking at the first line I can isolate the geometry by



st_geometry(rivers[1,8])



Geometry set for 1 feature
Geometry type: LINESTRING
Dimension: XYZ
Bounding box:  xmin: 462010.6 ymin: 1213039 xmax: 462306.5 ymax: 1213199
z_range:   zmin: 0 zmax: 0
Projected CRS: OSGB 1936 / British National Grid

LINESTRING Z (462306.5 1213048 0, 462275.4 1213...


What I need is all the values in the LINESTRING as a common or garden R
vector, but I cannot find a way to do this.

 Does anyone know how?  Thanks, Nick Wray

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Adding page numbers to existing PDFs

2022-10-21 Thread Dennis Fisher
R 4.2.1
OS X

Colleagues

I have multipage PDF files that were created in R — the files do NOT have page 
numbers.  I would like to add page numbers after the fact, i.e., read a file 
into R, add margin text, then output as a PDF.
Can this be done in R (base R or a package)?  
It can be done in Python using reportlab.pdfgen — however, the file size 
increases prohibitively.

Dennis

Dennis Fisher MD
P < (The "P Less Than" Company)
Phone / Fax: 1-866-PLessThan (1-866-753-7784)
www.PLessThan.com

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Ebert,Timothy Aaron
Is there a place where you would use ifelse()? I used it here because it was 
short and there was no indication of lots of data. In the example I cannot tell 
the difference of a few hundred milliseconds execution time. Benchmarking code 
is important for larger problems.

Tim

-Original Message-
From: Martin Maechler  
Sent: Friday, October 21, 2022 8:43 AM
To: Ebert,Timothy Aaron 
Cc: Andrew Simmons ; Jinsong Zhao ; R-help 
Mailing List 
Subject: Re: [R] unexpected 'else' in " else"

[External Email]

> Ebert,Timothy Aaron
> on Fri, 21 Oct 2022 12:05:58 + writes:

> I can get it to work with
> ifelse(is.matrix(r), r[w!=0, , drop=FALSE], r[w!=0])

Note that this is *not* good advice:

  if(Cnd) A else Bis very much more efficient  than
  ifelse(Cnd, A, B)

whenever it is appropriate, i.e.,
the condition Cnd is a simple TRUE or FALSE.

ifelse() is very much over-used!

{For the more sophisticated reader:
 In R, these both are function calls:
 `if` is a function of 3 argument with a "peculiar" syntax and  the third 
argument with default NULL.
}

Martin Maechler
ETH Zurich  and  R Core team



> With w and r as defined r is not a  matrix, so the first part will never 
execute. The test is for w not equal to zero so it is always true for these 
vectors. It is usually good to have test code such that all possible cases are 
activated.

> r<--1:8
> w<- -1:5
> if(is.matrix(r)){
> r[w!=0, , drop=FALSE]
> } else r[w != 0]

> I think this also works. The "else" must follow the } and you put in a 
carriage return after the }

> I think that is the answer, but not 100% sure.

> Tim

> -Original Message-
> From: R-help  On Behalf Of Andrew Simmons
> Sent: Friday, October 21, 2022 5:37 AM
> To: Jinsong Zhao 
> Cc: R-help Mailing List 
> Subject: Re: [R] unexpected 'else' in " else"

> [External Email]

> The error comes from the expression not being wrapped with braces. You 
could change it to

> if (is.matrix(r)) {
> r[w != 0, , drop = FALSE]
> } else r[w != 0]

> or

> {
> if (is.matrix(r))
> r[w != 0, , drop = FALSE]
> else r[w != 0]
> }

> or

> if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

>> Hi there,
>>
>> The following code would cause R error:
>>
>> > w <- 1:5
>> > r <- 1:5
>> > if (is.matrix(r))
>> + r[w != 0, , drop = FALSE]
>> > else r[w != 0]
>> Error: unexpected 'else' in "else"
>>
>> However, the code:
>> if (is.matrix(r))
>> r[w != 0, , drop = FALSE]
>> else r[w != 0]
>> is extracted from stats::weighted.residuals.
>>
>> My question is why the code in the function does not cause error?
>>
>> Best,
>> Jinsong
>>
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat
>> .ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl
>> .edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e
>> 1b84%7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4w
>> LjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>> sdata=9ImIUx0YyKjFMTDRrwa5fnkqiJL9aDjpGCRxxfI6Hlk%3Dreserved
>> =0
>> PLEASE do read the posting guide
>> 
https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r%2Fdata=05%7C01%7Ctebert%40ufl.edu%7Cd3824be0a76a4e488dda08dab361d1e6%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019529977132811%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=MTmSNg1tfjToCYtWtMf01Hhy93K0TpT3DPwuvYqVv0s%3Dreserved=0
>> -project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%
>> 7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%
>> 7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwM
>> DAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>> sdata=WsqoNk2NQ6NOjKoOKwf%2FPU57XkAwKtRhw6xb68COT1o%3Dreserved=0
>> and provide commented, minimal, self-contained, reproducible code.
>>

> [[alternative HTML version deleted]]

> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 
https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat.ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl.edu%7Cd3824be0a76a4e488dda08dab361d1e6%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019529977132811%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=5omzPR7XzgdKZG6pr0Ro%2F6hplvltKLHdDvNkOUVv5qM%3Dreserved=0
> PLEASE do read the 

Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Andrew Simmons
The code working inside stats::weighted.residuals has nothing to do
with being evaluated in a different environment than globalenv() and
has nothing to do with being inside a package.
The reason the code works inside stats::weighted.residuals is because
the function body is wrapped with braces. You can try it yourself:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("if (TRUE) \n'evaluating cons.expr'\nelse
'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(source(FILE, local = TRUE, echo = TRUE, verbose = FALSE))
})

If you try entering it as a function, it still fails:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("function () \nif (TRUE) \n'evaluating
cons.expr'\nelse 'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(source(FILE, local = TRUE, echo = TRUE, verbose = FALSE))
})

But R packages use sys.source() instead of source() to run R code, but
it still fails if you run it:

local({
FILE <- tempfile(fileext = ".R")
on.exit(unlink(FILE, force = TRUE, expand = FALSE), add = TRUE,
after = FALSE)
writeLines("if (TRUE) \n'evaluating cons.expr'\nelse
'evaluating alt.expr'", FILE)
writeLines(readLines(FILE))
try(sys.source(FILE, envir = environment()))
})

The part that matters is that the function body is wrapped with
braces. `if` statements inside braces or parenthesis (or possibly
brackets) will continue looking for `else` even after `cons.expr` and
a newline has been fully parsed, but will not otherwise.

On Fri, Oct 21, 2022 at 10:39 AM Jorgen Harmse via R-help
 wrote:
>
> Andrew Simmons is correct but doesn't explain why the code works in the 
> package. This is one of only two differences I have found between running 
> code at the command line and running it from a file. (The other difference is 
> that code in a file is often executed in an environment other than 
> .GlobalEnv. There is some related sugar around packages that usually makes 
> things work the way a user would want.) At the command line, R executes code 
> whenever RETURN could be interpreted as the end of a statement. "If(….) …. 
> RETURN" is ambiguous: will it be followed by "else", or is it a complete 
> statement? If it's in a file or wrapped in a block or other structure that 
> obviously hasn't ended yet then R will wait to see the next line of input, 
> but if it could be a complete statement then not executing it would cause a 
> lot of frustration for users. Once the statement is executed, R expects 
> another statement, and no statement begins with "else". (Maybe the 
> interpreter could be enhanced to keep the "if" open under some conditions, 
> but I haven't thought it through. In particular, "if" without "else" is NULL 
> if the condition is FALSE, so it might be necessary to undo an assignment, 
> and that seems very difficult.)
>
> Regards,
> Jorgen Harmse.
>
>
> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:
>
> > Hi there,
> >
> > The following code would cause R error:
> >
> >  > w <- 1:5
> >  > r <- 1:5
> >  > if (is.matrix(r))
> > + r[w != 0, , drop = FALSE]
> >  > else r[w != 0]
> > Error: unexpected 'else' in "else"
> >
> > However, the code:
> >  if (is.matrix(r))
> >  r[w != 0, , drop = FALSE]
> >  else r[w != 0]
> > is extracted from stats::weighted.residuals.
> >
> > My question is why the code in the function does not cause error?
> >
> > Best,
> > Jinsong
> >
> > __
> > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>
> [[alternative HTML version deleted]]
>
>
>
>
> --
>
> Subject: Digest Footer
>
> ___
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
> --
>
> End of R-help Digest, Vol 236, Issue 19
> ***
>
> [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see

Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Jorgen Harmse via R-help
Andrew Simmons is correct but doesn't explain why the code works in the 
package. This is one of only two differences I have found between running code 
at the command line and running it from a file. (The other difference is that 
code in a file is often executed in an environment other than .GlobalEnv. There 
is some related sugar around packages that usually makes things work the way a 
user would want.) At the command line, R executes code whenever RETURN could be 
interpreted as the end of a statement. "If(�.) �. RETURN" is ambiguous: will it 
be followed by "else", or is it a complete statement? If it's in a file or 
wrapped in a block or other structure that obviously hasn't ended yet then R 
will wait to see the next line of input, but if it could be a complete 
statement then not executing it would cause a lot of frustration for users. 
Once the statement is executed, R expects another statement, and no statement 
begins with "else". (Maybe the interpreter could be enhanced to keep the "if" 
open under some conditions, but I haven't thought it through. In particular, 
"if" without "else" is NULL if the condition is FALSE, so it might be necessary 
to undo an assignment, and that seems very difficult.)

Regards,
Jorgen Harmse.


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

> Hi there,
>
> The following code would cause R error:
>
>  > w <- 1:5
>  > r <- 1:5
>  > if (is.matrix(r))
> + r[w != 0, , drop = FALSE]
>  > else r[w != 0]
> Error: unexpected 'else' in "else"
>
> However, the code:
>  if (is.matrix(r))
>  r[w != 0, , drop = FALSE]
>  else r[w != 0]
> is extracted from stats::weighted.residuals.
>
> My question is why the code in the function does not cause error?
>
> Best,
> Jinsong
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]




--

Subject: Digest Footer

___
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


--

End of R-help Digest, Vol 236, Issue 19
***

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Jinsong Zhao

Dear John,

Thank you very much for the explanation. It cleared up my confusion 
about the syntax of "if ... else...", which in the help page of "if" said:

```
In particular, you should not have a newline between ‘}’ and
 ‘else’ to avoid a syntax error in entering a ‘if ... else’
 construct at the keyboard or via ‘source’.
```

Best,
Jinsong


On 2022/10/21 21:49, John Fox wrote:

Dear Jinsong,

When you enter these code lines at the R command prompt, the 
interpreter evaluates an expression when it's syntactically complete, 
which occurs before it sees the else clause. The interpreter can't 
read your mind and know that an else clause will be entered on the 
next line. When the code lines are in a function, the function body is 
enclosed in braces and so the interpreter sees the else clause.


As I believe was already pointed out, you can similarly use braces at 
the command prompt to signal incompleteness of an expression, as in


> {if (FALSE) print(1)
+ else print(2)}
[1] 2

I hope this helps,
 John



__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread John Fox

Dear Jinsong,

When you enter these code lines at the R command prompt, the interpreter 
evaluates an expression when it's syntactically complete, which occurs 
before it sees the else clause. The interpreter can't read your mind and 
know that an else clause will be entered on the next line. When the code 
lines are in a function, the function body is enclosed in braces and so 
the interpreter sees the else clause.


As I believe was already pointed out, you can similarly use braces at 
the command prompt to signal incompleteness of an expression, as in


> {if (FALSE) print(1)
+ else print(2)}
[1] 2

I hope this helps,
 John

--
John Fox, Professor Emeritus
McMaster University
Hamilton, Ontario, Canada
web: https://socialsciences.mcmaster.ca/jfox/
On 2022-10-21 8:06 a.m., Jinsong Zhao wrote:

Thanks a lot!

I know the first and third way to correct the error. The second way 
seems make me know why the code is correct in the function 
stats::weighted.residuals.


On 2022/10/21 17:36, Andrew Simmons wrote:
The error comes from the expression not being wrapped with braces. You 
could change it to


if (is.matrix(r)) {
    r[w != 0, , drop = FALSE]
} else r[w != 0]

or

{
    if (is.matrix(r))
        r[w != 0, , drop = FALSE]
    else r[w != 0]
}

or

if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

    Hi there,

    The following code would cause R error:

     > w <- 1:5
     > r <- 1:5
     >         if (is.matrix(r))
    +             r[w != 0, , drop = FALSE]
     >         else r[w != 0]
    Error: unexpected 'else' in "        else"

    However, the code:
             if (is.matrix(r))
                 r[w != 0, , drop = FALSE]
             else r[w != 0]
    is extracted from stats::weighted.residuals.

    My question is why the code in the function does not cause error?

    Best,
    Jinsong

    __
    R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
    https://stat.ethz.ch/mailman/listinfo/r-help
    PLEASE do read the posting guide
    http://www.R-project.org/posting-guide.html
    
    and provide commented, minimal, self-contained, reproducible code.



__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html

and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Martin Maechler
> Ebert,Timothy Aaron 
> on Fri, 21 Oct 2022 12:05:58 + writes:

> I can get it to work with
> ifelse(is.matrix(r), r[w!=0, , drop=FALSE], r[w!=0])

Note that this is *not* good advice:

  if(Cnd) A else Bis very much more efficient  than
  ifelse(Cnd, A, B)

whenever it is appropriate, i.e.,
the condition Cnd is a simple TRUE or FALSE.

ifelse() is very much over-used!

{For the more sophisticated reader:
 In R, these both are function calls:
 `if` is a function of 3 argument with a "peculiar" syntax and
 the third argument with default NULL.
}

Martin Maechler
ETH Zurich  and  R Core team



> With w and r as defined r is not a  matrix, so the first part will never 
execute. The test is for w not equal to zero so it is always true for these 
vectors. It is usually good to have test code such that all possible cases are 
activated.

> r<--1:8
> w<- -1:5
> if(is.matrix(r)){
> r[w!=0, , drop=FALSE]
> } else r[w != 0]

> I think this also works. The "else" must follow the } and you put in a 
carriage return after the }

> I think that is the answer, but not 100% sure.

> Tim

> -Original Message-
> From: R-help  On Behalf Of Andrew Simmons
> Sent: Friday, October 21, 2022 5:37 AM
> To: Jinsong Zhao 
> Cc: R-help Mailing List 
> Subject: Re: [R] unexpected 'else' in " else"

> [External Email]

> The error comes from the expression not being wrapped with braces. You 
could change it to

> if (is.matrix(r)) {
> r[w != 0, , drop = FALSE]
> } else r[w != 0]

> or

> {
> if (is.matrix(r))
> r[w != 0, , drop = FALSE]
> else r[w != 0]
> }

> or

> if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

>> Hi there,
>> 
>> The following code would cause R error:
>> 
>> > w <- 1:5
>> > r <- 1:5
>> > if (is.matrix(r))
>> + r[w != 0, , drop = FALSE]
>> > else r[w != 0]
>> Error: unexpected 'else' in "else"
>> 
>> However, the code:
>> if (is.matrix(r))
>> r[w != 0, , drop = FALSE]
>> else r[w != 0]
>> is extracted from stats::weighted.residuals.
>> 
>> My question is why the code in the function does not cause error?
>> 
>> Best,
>> Jinsong
>> 
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat
>> .ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl
>> .edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e
>> 1b84%7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4w
>> LjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>> sdata=9ImIUx0YyKjFMTDRrwa5fnkqiJL9aDjpGCRxxfI6Hlk%3Dreserved
>> =0
>> PLEASE do read the posting guide
>> https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r
>> -project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%
>> 7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%
>> 7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwM
>> DAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
>> sdata=WsqoNk2NQ6NOjKoOKwf%2FPU57XkAwKtRhw6xb68COT1o%3Dreserved=0
>> and provide commented, minimal, self-contained, reproducible code.
>> 

> [[alternative HTML version deleted]]

> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 
https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat.ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl.edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019419898095081%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=2mYpa25vpXNvPNINi9XxCtc7Vbj4Sp4IQUsA9fL%2BA60%3Dreserved=0
> PLEASE do read the posting guide 
https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r-project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019419898095081%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=21LO4e%2BNnGmlDjm3XfExMX63Z2viUePxMaHbcgm7JuA%3Dreserved=0
> and provide commented, minimal, self-contained, reproducible code.

> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, 

Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Jinsong Zhao

Thanks a lot!

I know the first and third way to correct the error. The second way 
seems make me know why the code is correct in the function 
stats::weighted.residuals.


On 2022/10/21 17:36, Andrew Simmons wrote:
The error comes from the expression not being wrapped with braces. You 
could change it to


if (is.matrix(r)) {
    r[w != 0, , drop = FALSE]
} else r[w != 0]

or

{
    if (is.matrix(r))
        r[w != 0, , drop = FALSE]
    else r[w != 0]
}

or

if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

Hi there,

The following code would cause R error:

 > w <- 1:5
 > r <- 1:5
 >         if (is.matrix(r))
+             r[w != 0, , drop = FALSE]
 >         else r[w != 0]
Error: unexpected 'else' in "        else"

However, the code:
         if (is.matrix(r))
             r[w != 0, , drop = FALSE]
         else r[w != 0]
is extracted from stats::weighted.residuals.

My question is why the code in the function does not cause error?

Best,
Jinsong

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html

and provide commented, minimal, self-contained, reproducible code.



__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Ebert,Timothy Aaron
I can get it to work with
ifelse(is.matrix(r), r[w!=0, , drop=FALSE], r[w!=0])

With w and r as defined r is not a  matrix, so the first part will never 
execute. The test is for w not equal to zero so it is always true for these 
vectors. It is usually good to have test code such that all possible cases are 
activated.

r<--1:8
w<- -1:5
if(is.matrix(r)){
  r[w!=0, , drop=FALSE]
} else r[w != 0]

I think this also works. The "else" must follow the } and you put in a carriage 
return after the }

I think that is the answer, but not 100% sure.

Tim

-Original Message-
From: R-help  On Behalf Of Andrew Simmons
Sent: Friday, October 21, 2022 5:37 AM
To: Jinsong Zhao 
Cc: R-help Mailing List 
Subject: Re: [R] unexpected 'else' in " else"

[External Email]

The error comes from the expression not being wrapped with braces. You could 
change it to

if (is.matrix(r)) {
r[w != 0, , drop = FALSE]
} else r[w != 0]

or

{
if (is.matrix(r))
r[w != 0, , drop = FALSE]
else r[w != 0]
}

or

if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

> Hi there,
>
> The following code would cause R error:
>
>  > w <- 1:5
>  > r <- 1:5
>  > if (is.matrix(r))
> + r[w != 0, , drop = FALSE]
>  > else r[w != 0]
> Error: unexpected 'else' in "else"
>
> However, the code:
>  if (is.matrix(r))
>  r[w != 0, , drop = FALSE]
>  else r[w != 0]
> is extracted from stats::weighted.residuals.
>
> My question is why the code in the function does not cause error?
>
> Best,
> Jinsong
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat
> .ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl
> .edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e
> 1b84%7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4w
> LjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
> sdata=9ImIUx0YyKjFMTDRrwa5fnkqiJL9aDjpGCRxxfI6Hlk%3Dreserved
> =0
> PLEASE do read the posting guide
> https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r
> -project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%
> 7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%
> 7C0%7C0%7C638019419897938843%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwM
> DAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C
> sdata=WsqoNk2NQ6NOjKoOKwf%2FPU57XkAwKtRhw6xb68COT1o%3Dreserved=0
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstat.ethz.ch%2Fmailman%2Flistinfo%2Fr-helpdata=05%7C01%7Ctebert%40ufl.edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019419898095081%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=2mYpa25vpXNvPNINi9XxCtc7Vbj4Sp4IQUsA9fL%2BA60%3Dreserved=0
PLEASE do read the posting guide 
https://nam10.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.r-project.org%2Fposting-guide.htmldata=05%7C01%7Ctebert%40ufl.edu%7C98bd495a0754455cbead08dab348311f%7C0d4da0f84a314d76ace60a62331e1b84%7C0%7C0%7C638019419898095081%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7Csdata=21LO4e%2BNnGmlDjm3XfExMX63Z2viUePxMaHbcgm7JuA%3Dreserved=0
and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Opening shapefiles in R

2022-10-21 Thread Nick Wray
Hello

I have managed to download and plot the outline for the River Tweed In the
Sottish borders)  catchment using this code.  21009 is a zipfile downloaded
from the FEH website https://fehweb.ceh.ac.uk/Map:

require(rgdal)

shape <- readOGR(dsn ="C:/Users/nick/Desktop/PhD Oct 22", layer = "21009")

shape

plot(shape)

and I get an outline of the Tweed catchment which I can use

the zipfile has eight documents all with the name “21009.” and the suffixes
cpg/dbf/prj/sbn/sbx/shp/shp/shx   There are two .shp docs, one labelled as
SHP file and one as XML file.

However

I then have downloaded a file of a plot of all the rivers in the uk from
https://osdatahub.os.uk/downloads/open

I’ve put this data into a zipfile with the name “rivers”   Within this are
eight docs – four with the names HydroNode. and suffixes dbf/prj/shp/shx
and four with the name WatercourseLink. and the four suffixes.

Just subbing in “rivers” for “21009” in my code above doesn’t work and I
can’t find a way of getting into the shapefiles and opening them


I'd be grateful if anyone can help me get further with this

Thanks Nick Wray

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] unexpected 'else' in " else"

2022-10-21 Thread Andrew Simmons
The error comes from the expression not being wrapped with braces. You
could change it to

if (is.matrix(r)) {
r[w != 0, , drop = FALSE]
} else r[w != 0]

or

{
if (is.matrix(r))
r[w != 0, , drop = FALSE]
else r[w != 0]
}

or

if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao,  wrote:

> Hi there,
>
> The following code would cause R error:
>
>  > w <- 1:5
>  > r <- 1:5
>  > if (is.matrix(r))
> + r[w != 0, , drop = FALSE]
>  > else r[w != 0]
> Error: unexpected 'else' in "else"
>
> However, the code:
>  if (is.matrix(r))
>  r[w != 0, , drop = FALSE]
>  else r[w != 0]
> is extracted from stats::weighted.residuals.
>
> My question is why the code in the function does not cause error?
>
> Best,
> Jinsong
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] unexpected 'else' in " else"

2022-10-21 Thread Jinsong Zhao

Hi there,

The following code would cause R error:

> w <- 1:5
> r <- 1:5
> if (is.matrix(r))
+ r[w != 0, , drop = FALSE]
> else r[w != 0]
Error: unexpected 'else' in "else"

However, the code:
if (is.matrix(r))
r[w != 0, , drop = FALSE]
else r[w != 0]
is extracted from stats::weighted.residuals.

My question is why the code in the function does not cause error?

Best,
Jinsong

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] inconsistencies between HLM and clmm results for the signs for the coefficients

2022-10-21 Thread Thierry Onkelinx via R-help
Dear Debbie,

Have a look at the vignette of the ordinal package. Look for the equation
that defines \eta. And note the minus sign associated with \beta. You'll
need to find the equation used in HLM and compare it with the equation from
ordinal.

Best regards,

ir. Thierry Onkelinx
Statisticus / Statistician

Vlaamse Overheid / Government of Flanders
INSTITUUT VOOR NATUUR- EN BOSONDERZOEK / RESEARCH INSTITUTE FOR NATURE AND
FOREST
Team Biometrie & Kwaliteitszorg / Team Biometrics & Quality Assurance
thierry.onkel...@inbo.be
Havenlaan 88 bus 73, 1000 Brussel
www.inbo.be

///
To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to say
what the experiment died of. ~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data. ~ Roger Brinner
The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey
///




Op do 20 okt. 2022 om 09:22 schreef Debbie Hahs-Vaughn :

> I've generated a very simple multilevel ordinal model using HLM software
> and using the clmm function from the ordinal package in R. The threshold
> values and coefficients are comparable, however the signs for the
> coefficients (and only the coefficients; not the thresholds) are opposite
> (e.g., positive in HLM, negative in clmm).  This then impacts the odds
> ratios for the predictors.  HLM reports odds greater than one and clmm
> reports odds less than one.  I anticipate there is a very easy reason for
> what's happening, and it's just escaping me.  Can someone please advise on
> what I've overlooked?
>
> [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.