Re: [R] [EXT] Theta from negative binomial regression and power_NegativeBinomiial from PASSED

2023-09-14 Thread Andrew Robinson via R-help
Hi John, the negative binomial is a tricky one - there are several different parameterisations and therefore different interpretations of the parameters. Joseph Hilbe wrote a whole book on it that might be wroth checking. Cheers, Andrew -- Andrew Robinson Chief Executive Officer, CEBRA

Re: [R] [EXT] Downloading a directory of text files into R

2023-07-25 Thread Andrew Robinson via R-help
Hi Bob, there may be more efficient ways to go about it but I would use R to scrape the contents of http://home.brisnet.org.au/~bgreen/Data/Hanson1/ http://home.brisnet.org.au/~bgreen/Data/Hanson2/ in order to form the URLs of the files, and then loop over the URLs. Cheers, Andrew -- Andrew

[R] caret package

2023-07-10 Thread Andrew Zhang
2.00 GHz, 8 cores 16.0 GB Does anyone know if my script has any issues, or it is normal for sbf() to run this long? Thank you! Andrew > sessionInfo() R version 4.3.1 (2023-06-16 ucrt) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19045) Matrix products

[R] Feature selection for multiclass classification

2023-06-16 Thread Andrew Zhang
ges/methods for feature selection prior to building a classification model using machine learning models. Thanks, Andrew [[alternative HTML version deleted]] __ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz

Re: [R] can't install nser...

2023-04-09 Thread Andrew Simmons
It says that nser requires the most recent version of magrittr that you do not have installed. You must update magrittr before attempting to install nser: update.packages(oldPkgs = "magrittr") or at the prompt you were presented before, choose to update magrittr before installing nser. On Sun,

Re: [R] Removing variables from data frame with a wile card

2023-02-12 Thread Andrew Simmons
What I meant is that that mydata[, !grepl("^yr", colnames(mydata)), drop = FALSE] and mydata[!grepl("^yr", colnames(mydata))] should be identical. Some people would prefer the first because the indexing looks the same as matrix indexing, whereas some people would prefer the second because it

Re: [R] Removing variables from data frame with a wile card

2023-02-12 Thread Andrew Simmons
he object in the column is the same character vector. You could alternatively use x["V2"] which should be identical to x[, "V2", drop = FALSE], but some people don't like that because it doesn't look like matrix indexing anymore. On Sun, Feb 12, 2023, 17:18 Steven T. Yen wrote:

Re: [R] preserve class in apply function

2023-02-07 Thread Andrew Simmons
It is not possible, apply() converts its argument to an array. You might be able to use split() and lapply() to solve your problem. On Tue, Feb 7, 2023, 07:52 Naresh Gurbuxani wrote: > > > Consider a data.frame whose different columns have numeric, character, > > and factor data. In apply

Re: [R] [EXT] How to calculate the derivatives at each data point?

2023-01-31 Thread Andrew Robinson via R-help
Try something like with(df, predict(smooth.spline(x = altitude, y = atm_values), deriv = 1)) Cheers, Andrew -- Andrew Robinson Chief Executive Officer, CEBRA and Professor of Biosecurity, School/s of BioSciences and Mathematics & Statistics University of Melbourne, VIC 3010 Australia Tel:

Re: [R] implicit loop for nested list

2023-01-26 Thread Andrew Simmons
I would use replicate() to do an operation with random numbers repeatedly: ``` mysim <- replicate(10, { two.mat <- matrix(rnorm(4), 2, 2) four.mat <- matrix(rnorm(16), 4, 4) list(two.mat = two.mat, four.mat = four.mat) }) ``` which should give you a matrix-list. You can slice this

Re: [R] Minimal match to regexp?

2023-01-25 Thread Andrew Simmons
> > I need to have the same number of backticks in the opening and closing > marker. So I make the pattern more complicated, and it doesn't work: > >pattern2 <- "\n([`]{3,})html\n.*?\n\\1\n" > > This matches all of x: > >> pattern2 <- &q

Re: [R] Minimal match to regexp?

2023-01-25 Thread Andrew Simmons
grep(value = TRUE) just returns the strings which match the pattern. You have to use regexpr() or gregexpr() if you want to know where the matches are: ``` x <- "abaca" # extract only the first match with regexpr() m <- regexpr("a.*?a", x) regmatches(x, m) # or # extract every match with

Re: [R] as.factor and floating point numbers

2023-01-25 Thread Andrew Simmons
R converts floats to strings with ~15 digits of accuracy, specifically to avoid differentiating between 1 and 1 + .Machine$double.eps, it is assumed that small differences such as this are due to rounding errors and are unimportant. So, if when making your factor, you want all digits, you could

Re: [R] Partial matching with $ extractor.

2023-01-24 Thread Andrew Simmons
I tried this again with R 2.15.3, the oldest version I have installed, and I still got the same behaviour. It extracts the first exact match, then the only partial match, then NULL. On Tue, Jan 24, 2023 at 5:04 PM Rolf Turner wrote: > > > Has something changed, but I missed it? > > My

Re: [R] Partial matching with $ extractor.

2023-01-24 Thread Andrew Simmons
junk$y extracts the element named "y" because it found an exact match for the name. junk$yu extracts nothing because it does not find an exact match and finds multiple partial matches. junk$yuc or junk$yur would work because it finds no exact match and then exactly one partial match. On Tue,

Re: [R] Removing variables from data frame with a wile card

2023-01-13 Thread Andrew Simmons
You'll want to use grep() or grepl(). By default, grep() uses extended regular expressions to find matches, but you can also use perl regular expressions and globbing (after converting to a regular expression). For example: grepl("^yr", colnames(mydata)) will tell you which 'colnames' start with

Re: [R] return value of {....}

2023-01-09 Thread Andrew Simmons
Returning the last value of { is the basis of functions not needing a return statement. Before R invokes a function (specifically a closure), it creates a new context. When R evaluates a call to return, it looks for a context to return from and finds the context of function, ending the context and

Re: [R] Problem with integrate(function(x) x^3 / sin(x), -pi/2, pi/2)

2023-01-07 Thread Andrew Simmons
) works perfectly fine and is a better function definition anyway. `integrate` in the {stats} package is unlikely to change, so use the alternate function definition or use {pracma}. On Sat, Jan 7, 2023 at 10:41 PM Leonard Mada wrote: > > Dear Andrew, > > > The limit when x appro

Re: [R] Problem with integrate(function(x) x^3 / sin(x), -pi/2, pi/2)

2023-01-07 Thread Andrew Simmons
You're dividing 0 by 0, giving you NaN, perhaps you should try function(x) ifelse(x == 0, 0, x^3/sin(x)) On Sat, Jan 7, 2023, 22:24 Leonard Mada via R-help wrote: > Dear List-Members, > > I encounter a problem while trying to integrate the following function: > > integrate(function(x) x^3 /

Re: [R] Date order question

2023-01-04 Thread Andrew Simmons
I converted `date` to a factor and it seemed to work: ``` library(ggplot2) library(cowplot) date <- c("12-29","12-30","01-01") date <- factor(date, labels = unique(date)) PT <- c(.106,.130,.121) data <- data.frame(date,PT) ggplot(data, aes(x=date,y=PT,group=1))+ geom_point(size=4)+

Re: [R] Pipe operator

2023-01-03 Thread Andrew Hart via R-help
Keep in mind that in thie example you're processing x and placing the result back in x (so x must already exist). You can write this a bit more cleanly using the -> variant of the assignment operator as follows: x |> cos() |> max(pi/4) |> round(3) -> x Hth, Andrew. On

Re: [R] error in exists.....

2022-12-27 Thread Andrew Simmons
exists() is for bindings in an environment, not for names in a list. try "T1A1" %in% names(E$L[[i]]) instead On Tue, Dec 27, 2022, 12:36 akshay kulkarni wrote: > Dear members, > I have the following code: > > E <- new.env() > > E$L <- list() > > i <- 1 > >

Re: [R] difference between script and a function....

2022-12-24 Thread Andrew Simmons
1. The execution environment for a script is the global environment. Each R script run from a shell will be given its own global environment. Each R session has exactly one global environment, but you can have several active R sessions. 2. Using return in a script instead of a function will throw

Re: [R] interval between specific characters in a string...

2022-12-02 Thread Andrew Hart via R-help
ach of these in order to obtain the correct interval sizes. Hth, Andrew. On 2/12/2022 14:18, Evan Cooch wrote: Was wondering if there is an 'efficient/elegant' way to do the following (without tidyverse). Take a string abaaabbabaaab Its easy enough to count the number of times the character 'b' sh

Re: [R] interval between specific characters in a string...

2022-12-02 Thread Andrew Simmons
try gregexpr('b+', target_string) which looks for one or more b characters, then get the attribute "match.length" On Fri, Dec 2, 2022, 18:56 Evan Cooch wrote: > Was wondering if there is an 'efficient/elegant' way to do the following > (without tidyverse). Take a string > > abaaabbabaaab

Re: [R] Format printing with R

2022-11-21 Thread Andrew Simmons
For print(), digits is the minimal number of significant digits. In your case, rounding the first column to the 3rd decimal place gives at least 2 sigfigs and rounding the second column to the 2nd decimal place. If you want to print all numbers to two significant digits, regardless of what other

Re: [R] Rare behaviour for nlme::reStruct example and question about ?lmeObject

2022-11-15 Thread Andrew Simmons
This seems to be a bug. I tried creating this function in the global environment: str.pdMat <- function (object, ...) { if (nlme::isInitialized(object)) { NextMethod() } else { cat(" Uninitialized positive definite matrix structure of class ",

Re: [R] print and lapply....

2022-11-07 Thread Andrew Simmons
e return list in any way. On Mon, Nov 7, 2022 at 12:38 PM akshay kulkarni wrote: > > Dear Andrew > It doesn't work: > > > lapply(TP,function(x){print(x^2)}) > [1] 1 > [1] 4 > [1] 9 > [1] 16 > [[1]] > [1] 1 > > [[2]] > [1] 4

Re: [R] print and lapply....

2022-11-07 Thread Andrew Simmons
put print() around x^2 On Mon, Nov 7, 2022, 12:18 akshay kulkarni wrote: > Dear members, > I have the following code and output: > > > TP <- 1:4 > > lapply(TP,function(x){print(x);x^2}) > [1] 1 > [1] 2 > [1] 3 > [1] 4 > [[1]] > [1] 1 > > [[2]] > [1] 4 > > [[3]] >

Re: [R] Associate a .R file with the RGui

2022-11-04 Thread Andrew Simmons
In an R session, run this: writeLines(normalizePath(R.home("bin"))) Right click your .R file > Open with > Choose another app > Check the box "Always use this app to open .R files" > Look for another app on this PC Paste the directory found above, then select "Rgui.exe" On Fri, Nov 4, 2022,

Re: [R] Unexpected result for df column $ subset with non-existent name

2022-10-30 Thread Andrew Simmons
partial match attr is for something like attr(data.frame(), "cla") which will partially match to "class". On Sun, Oct 30, 2022, 12:55 Joshua Ulrich wrote: > For what it's worth, I set these options to warn me about partial matches: > > options(warnPartialMatchArgs = TRUE, >

Re: [R] Partition vector of strings into lines of preferred width

2022-10-28 Thread Andrew Simmons
I would suggest using strwrap(), the documentation at ?strwrap has plenty of details and examples. For paragraphs, I would usually do something like: strwrap(x = , width = 80, indent = 4) On Fri, Oct 28, 2022 at 5:42 PM Leonard Mada via R-help wrote: > > Dear R-Users, > > text = " > What is the

Re: [R] $ subset operator behavior in lapply

2022-10-27 Thread Andrew Simmons
$ does not evaluate its second argument, it does something like as.character(substitute(name)). You should be using lapply(list, function(x) x$a) or lapply(list, `[[`, "a") On Thu, Oct 27, 2022, 12:29 Hilmar Berger wrote: > Dear all, > > I'm a little bit surprised by the behavior of the $

Re: [R] When using require(), why do I get the error message "Error in if (!loaded) { : the condition has length > 1" ?

2022-10-24 Thread Andrew Simmons
'base' ), what is the "first argument"? > > On Mon, Oct 24, 2022 at 12:29 PM Andrew Simmons > wrote: > > > > require(), similarly to library(), does not evaluate its first argument > UNLESS you add character.only = TRUE > > > > require( packages_i_wan

Re: [R] When using require(), why do I get the error message "Error in if (!loaded) { : the condition has length > 1" ?

2022-10-24 Thread Andrew Simmons
require(), similarly to library(), does not evaluate its first argument UNLESS you add character.only = TRUE require( packages_i_want_to_use[1], character.only = TRUE) On Mon, Oct 24, 2022, 12:26 Kelly Thompson wrote: > # Below, when using require(), why do I get the error message "Error > in

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

2022-10-21 Thread Andrew Simmons
nt())) }) 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

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

Re: [R] Help installing devtools plus other packages in R terminal

2022-10-06 Thread Andrew Simmons
To install the packages from source, you need to install make, gcc, and g++: ⁠sudo apt install make⁠ ⁠sudo apt install gcc⁠ ⁠sudo apt install g++ then try installing them again On Thu, Oct 6, 2022 at 2:54 AM Rhon Calderon, Eric wrote: > > Hi, > > I am using R in my HPC terminal. After many

[R] Problem with Windows clipboard and UTF-8

2022-09-30 Thread Andrew Hart via R-help
e of holding Unicode text. Any advice would be gratefully received. Thanks, Andrew. __ 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

Re: [R] How to set default encoding for sourced files

2022-09-23 Thread Andrew Hart via R-help
the need to set options or specify the encoding with Rscript. Very nice and kudos to the R developers for taking the leap! Thanks everyone for your help. Cheers, Andrew. On 21/09/2022 16:40, Andrew Simmons wrote: If you're running it from Rscript, you'll have to specify the encoding like

Re: [R] [Rd] Problem with accessibility in R 4.2.0 and 4.2.1.

2022-09-23 Thread Andrew Hart via R-help
I was logged in remotely. Text-based help is fine when ssh-ing into a machine, but HTML help is much nicer to read and navigate. I think I'll just switch over to Rterm for a while, but I can also check out ess, which I wasn't aware of. Thanks a lot, Andrew.

Re: [R] Fatal Error: Contains Space

2022-09-22 Thread Andrew Simmons
Hello, I'm going to quote the tempdir() doc page: "By default, tmpdir will be the directory given by tempdir(). This will be a subdirectory of the per-session temporary directory found by the following rule when the R session is started. The environment variables TMPDIR, TMP and TEMP are checked

Re: [R] S4 dispatch ambiguity

2022-09-21 Thread Andrew Simmons
In the first scenario, your object is class AB, then class A with distance 1, then class B with distance 2. This means that method A is preferable since it is less distance away than method B. However, in your second function, both methods are a total distance of 3 away, so (as far as I know) it

Re: [R] How to set default encoding for sourced files

2022-09-21 Thread Andrew Simmons
and not have any issues. Are you using an older version of R? On Wed., Sep. 21, 2022, 14:20 Andrew Hart via R-help, wrote: > On 21/09/2022 11:46, Bert Gunter wrote: > > ?options > > > > options(encoding = "utf-8") > > in a startup file or function should presum

Re: [R] Error in if (class(networks) == "matrix") from a function

2022-09-21 Thread Andrew Simmons
In general, you should be using inherits(netwotks, "matrix") or is(networks, "matrix") instead of class() == Your function fails because your object has multiple classes so class== returns multiple logical values so if will fail. But inherits or is will return one logical value, so if will not

Re: [R] How to set default encoding for sourced files

2022-09-21 Thread Andrew Hart via R-help
ource to read in the R script. Mind you, if I do Rscript -e source('myfile.R') it works properly just like in Rgui. Once again, Thanks heaps. Cheers, Andrew. __ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/li

[R] How to set default encoding for sourced files

2022-09-21 Thread Andrew Hart via R-help
environment variable I can set or some other way to instruct R to always assume that input stream encodings will be utf-8 unless otherwise specified? This way, I would only ever have to supply an encoding or fileEncoding argument to specify "latin1" if I happ en to encou

[R] Returning Visibly / / Invisibly from C Function

2022-09-16 Thread Andrew Simmons
Hello, I'm working on a function envvars() which I'd like to get, set, and remove environment variables in a manner similar to options(). At the R level, I have this function: envvars <- function (...) .External2(C_envvars, pairlist(...)) and then at the C level: #define set_R_Visible(X)

Re: [R] inadequacy in as.integer....

2022-09-11 Thread Andrew Simmons
What you're asking for doesn't make sense: 9098 and 09098 are the same 9098L == 09098L If you mean specifically while printing, you could use sprintf: cat(sprintf("%05d", 9098)) On Sun., Sep. 11, 2022, 14:58 akshay kulkarni, wrote: > Dear Tim, > So there is no way to coerce

Re: [R] inconsistency in switch statements.....

2022-09-07 Thread Andrew Simmons
1 and 2 are not valid identifiers in R, so you need to surround them with backticks to make them valid, the same as quoting a string: switch(Stst, `1` = print("NO"), `2` = print("YES")) On Wed., Sep. 7, 2022, 14:35 akshay kulkarni, wrote: > Dear members, > The

Re: [R] expand a matrix

2022-09-05 Thread Andrew Simmons
You can specify multiple indexes to replace at once, so you can avoid a for loop entirely like this: M <- matrix(nrow = 10, ncol = 10) M[1:4, 5: 6] <- M[5: 6, 1:4] <- m[1, 2] M[1:4,7] <- M[ 7, 1:4] <- m[1, 3] M[1:4, 8:10] <- M[8:10, 1:4] <- m[1, 4] M[5:6,7] <- M[ 7, 5:6] <- m[2, 3]

Re: [R] Read excel specific column

2022-08-23 Thread Andrew Simmons
I like package openxlsx, with the function openxlsx::read.xlsx() Another common package that people use readxl On Tue., Aug. 23, 2022, 7:51 p.m. Anas Jamshed, wrote: > I have .xlsx files with gene names in first column.How can read and load in > R? > > [[alternative HTML version

Re: [R] grep

2022-07-10 Thread Andrew Simmons
?regex is a nice starting point, it's got plenty of details on meta characters and characters classes, if you need more advanced stuff you'll probably have to look at the perl regex documentation, I believe it's linked in ?regex. I might try something like grep("^[xz]\\.") or grep("^[xz][.]")

Re: [R] Obtaining the source code

2022-06-19 Thread Andrew Simmons
You can use getAnywhere On Sun, Jun 19, 2022, 13:23 Christofer Bogaso wrote: > Hi, > > I am trying to see the source code of rstandard function. I tried below, > > > methods('rstandard') > > [1] rstandard.glm* rstandard.lm* > > What do I need to do if I want to see the source code of

Re: [R] How to improve accuracy of output?

2022-05-24 Thread Andrew Simmons
I think you have to use print(df$price, digits = 14) On Tue, May 24, 2022, 10:01 maithili_shiva--- via R-help < r-help@r-project.org> wrote: > Dear Forum > In my code, I am trying to compute Value at risk. > I have an issue as mentioned below: > I have defined > > > options(digits = 14) > But my

Re: [R] Somewhat disconcerting behavior of seq.int()

2022-05-02 Thread Andrew Simmons
A sequence where 'from' and 'to' are both integer valued (not necessarily class integer) will use R_compact_intrange; the return value is an integer vector and is stored with minimal space. In your case, you specified a 'from', 'to', and 'by'; if all are integer class, then the return value is

Re: [R] Time Zone problems: midnight goes in; 8am comes out

2022-03-01 Thread Andrew Simmons
It seems like the current version of lubridate is 1.8.0, which does raise a warning for an invalid timezone, just like as.POSIXct. This is what I tried: print(lubridate::parse_date_time("1970-01-01 00:01:00", "ymd HMS" , tz = "PST")) print(as.POSIXct("1970-01-01

Re: [R] Why does the print method fail for very small numbers?

2022-02-17 Thread Andrew Simmons
It should also be noted that format(x, digits = 17) instead of as.character(x) won't lose any accuracy. On Thu, Feb 17, 2022, 17:41 Marius Hofert wrote: > Dear expeRts, > > I'm familiar with IEEE 754. Is there an easy way to explain why even > just printing of small numbers fails? > > 1e-317 #

Re: [R] Help with developing package DWLS

2022-01-11 Thread Andrew Simmons
The NOTE saying 'Possibly misspelled words in DESCRIPTION' can probably be ignored (though I would probably put the name of your package in single quotes). The NOTE 'Non-standard files/directories found at top level' means that you should move the non-standard files to a different location OR

Re: [R] question about for loop

2021-12-24 Thread Andrew Simmons
y, c, and f only exist in the context of mac2 If you want to use them, you'll have to write mac2$y, mac2$c, or mac2$f (or the [[ versions mac2[["y"]], mac2[["c"]], or mac2[["f"]]) Combining that with index i would then look like mac2$y[[i]] or mac2[[i, "y"]] Also, I think you want to use

Re: [R] for loop question in R

2021-12-22 Thread Andrew Simmons
nrow() is just the numbers of rows in your data frame, use seq_len(nrow()) or seq(nrow()) to loop through all row numbers On Wed, Dec 22, 2021, 12:08 Kai Yang via R-help wrote: > Hello R team,I want to use for loop to generate multiple plots with 3 > parameter, (y is for y axis, c is for color

Re: [R] Bug in list.files(full.names=T)

2021-12-20 Thread Andrew Simmons
I've tried a bunch of different R versions, I can't seem to replicate what you described. Here's the code I used: R.pattern <- paste0("^R-", .standard_regexps()$valid_R_system_version, "$") x <- list.files(dirname(R.home()), pattern = R.pattern, full.names = TRUE) x <- x[file.info(x, extra_cols

Re: [R] A technical question on methods for "+"

2021-12-02 Thread Andrew Simmons
> classes which UseMethod() uses, is available as .class2(x) since R > version 4.0.0. (This also applies to S4 objects when S3 dispatch is > considered, see below.)" > > I think this is the "official" explanation, but I find it rather opaque. > > Thanks t

Re: [R] A technical question on methods for "+"

2021-12-02 Thread Andrew Simmons
This is because + dispatches on the class attribute, which a string like "test" has set to NULL, so it doesn't dispatch. You can add the class yourself like structure("test", class = "character") and that should work. I'm not sure where it's explained, but most primitive functions dispatch on the

Re: [R] Degree symbol as axis label superscript

2021-11-30 Thread Andrew Simmons
this to the UTF-8 encoding that > **should** display as a "degree" symbol, subject to the above > referenced caveats. > Hence: > > intToUtf8(176) > [1] "°" ##degree character > > ## So, for example, you can do: > > degrF <-paste0(intToUtf8(176),&

Re: [R] Degree symbol as axis label superscript [RESOLVED]

2021-11-30 Thread Andrew Simmons
ard wrote: > > > Thanks, Andrew. I will. > > plotmath didn't have the solution; the use of the LaTeX ^ for a superscript > had a character or number preceeding it. Using 'degree' prints that string > on the axis. > > What does work is using the unicode for the degree symbo

Re: [R] Degree symbol as axis label superscript

2021-11-30 Thread Andrew Simmons
Excuse my brevity, but take a look at ?plotmath It has tons of tips for making pretty labels On Tue, Nov 30, 2021, 14:05 Rich Shepard wrote: > I want to present the temperature on the Y-axis label as 'Water Temperature > (oC)' with the degree symbol as a superscript. > > My web search found a

Re: [R] Is 'temp' a reserved/key word in R?

2021-11-30 Thread Andrew Simmons
It seems like the headers are misnamed, that should be a comma between sampdate and param, not a period On Tue, Nov 30, 2021, 09:35 Rich Shepard wrote: > A short data file: > site_nbr,sampdate.param,quant,unit > 31731,2005-07-12,temp,19.7,oC > 31731,2007-03-28,temp,9,oC >

Re: [R] Date read correctly from CSV, then reformatted incorrectly by R

2021-11-20 Thread Andrew Simmons
type to 'Date', however, the date is reconfigured. > For instance, 15/01/2010 (15 January 2010), becomes 0015-01-20. > > > > I've tried ```data_long$Date <- as.Date(data_long$Date, format = > "%d/%m.%y")```, and also ```tryformat c("%d/%m%y")```, but either the error &

Re: [R] Dispatching on 2 arguments?

2021-11-07 Thread Andrew Simmons
If you want to use the 'methods' package, you could do something like: replace <- function (p1, p2, ...) { stop(gettextf("cannot 'replace' with arguments of class %s and %s", sQuote(class(p1)[1L]), sQuote(class(p2)[1L]))) } methods::setGeneric("replace")

Re: [R] names.data.frame?

2021-11-03 Thread Andrew Simmons
First, your signature for names.pm is wrong. It should look something more like: names.pm <- function (x) { } As for the body of the function, you might do something like: names.pm <- function (x) { NextMethod() } but you don't need to define a names method if you're just going to call

Re: [R] sink() not working as expected

2021-11-02 Thread Andrew Simmons
cat in R behaves similarly to cat in unix-alikes, sends text to a stdout. Usually, that stdout would be a file, but usually in R it is the R Console. I think it might also help to note the difference between cat and print: x <- "test\n" cat(x) print(x) produces > cat(x) test > print(x) [1]

Re: [R] sink() not working as expected

2021-11-02 Thread Andrew Simmons
You probably want to use cat and print for these lines. These things won't print when not run at the top level, so if you want them to print, you must specify that. On Tue, Nov 2, 2021, 13:18 Rich Shepard wrote: > I've read ?sink and several web pages about it but it's not working > properly >

Re: [R] Is there a hash data structure for R

2021-11-02 Thread Andrew Simmons
If you're thinking about using environments, I would suggest you initialize them like x <- new.env(parent = emptyenv()) Since environments have parent environments, it means that requesting a value from that environment can actually return the value stored in a parent environment (this isn't

Re: [R] by group

2021-11-01 Thread Andrew Simmons
I would usually use 'tapply'. It splits an object into groups, performs some function on each group, and then (optionally) converts the input to something simpler. For example: tapply(dat$wt, dat$Year, mean) # mean by Year tapply(dat$wt, dat$Sex , mean) # mean by Sex tapply(dat$wt,

Re: [R] generate random numeric

2021-10-29 Thread Andrew Simmons
It might not be random, depending upon a seed being used (usually by set.seed or RNGkind). However, it's the best method for generating a random number within a specified range without weights. If you want weights, there are many other random number generation functions, most notably rnorm. You

Re: [R] here Package

2021-10-17 Thread Andrew Simmons
You've just got the brackets in the wrong spot: creditsub <- read.csv(unz(here::here("Data.zip"), "creditcardsub.csv")) instead of creditsub <- read.csv(unz(here::here("Data.zip", "creditcardsub.csv"))) Also, you probably want to save that connection and close it manually. creditsub <-

Re: [R] How to select given row of conditionally subsetted dataframe?

2021-10-14 Thread Andrew Simmons
You're missing a comma, this should fix it df[(df$Y>0.2) & (df$X<10),][2, ] On Thu, Oct 14, 2021, 03:51 Luigi Marongiu wrote: > Hello, > I have selected a subset of a dataframe with the vector syntax (if > this is the name): > ``` > > df[(df$Y>0.2) & (df$X<10),] > YX > 10

Re: [R] unexpected behavior in apply

2021-10-08 Thread Andrew Simmons
Hello, The issue comes that 'apply' tries to coerce its argument to a matrix. This means that all your columns will become character class, and the result will not be what you wanted. I would suggest something more like: sapply(d, function(x) all(x[!is.na(x)] <= 3)) or vapply(d, function(x)

Re: [R] Rename variables starting with digits

2021-10-05 Thread Andrew Simmons
Hello, I think you have to use 'matches' instead of 'starts_with', I believe starts_with does not accept a regular expression whereas matches does. On Tue, Oct 5, 2021 at 12:15 PM Anne Zach wrote: > Dear R users, > > I have a dataframe that contains several variables, among which 105 >

Re: [R] Word-Wrapper Library/Package?

2021-09-28 Thread Andrew Simmons
such a thing. If such a thing exists in another language, there's probably an R package with a similar name containing ports of such functions, that might be your best bet. I hope this helps. On Tue, Sep 28, 2021, 23:51 Leonard Mada wrote: > Thank you Andrew. > > > I will explore t

Re: [R] Word-Wrapper Library/Package?

2021-09-28 Thread Andrew Simmons
I think what you're looking for is 'strwrap', it's in package base. On Tue, Sep 28, 2021, 22:26 Leonard Mada via R-help wrote: > Dear R-Users, > > > Does anyone know any package or library that implements functions for > word wrapping? > > > I did implement a very rudimentary one (Github link

Re: [R] Improvement: function cut

2021-09-17 Thread Andrew Simmons
i = TRUE), check.names = FALSE ) I hope this helps. On Fri, Sep 17, 2021 at 6:26 PM Leonard Mada wrote: > Hello Andrew, > > > But "cut" generates factors. In most cases with real data one expects to > have also the ends of the interval: the argument "include.lowest" is

Re: [R] Improvement: function cut

2021-09-17 Thread Andrew Simmons
e default of 'include.lowest'. I hope this helps On Fri, Sep 17, 2021 at 6:01 PM Leonard Mada wrote: > Thank you Andrew. > > > Is there any reason not to make: include.lowest = TRUE the default? > > > Regarding the NA: > > The user still has to suspect that some values w

Re: [R] Improvement: function cut

2021-09-17 Thread Andrew Simmons
Regarding your first point, argument 'include.lowest' already handles this specific case, see ?.bincode Your second point, maybe it could be helpful, but since both 'cut.default' and '.bincode' return NA if a value isn't within a bin, you could make something like this on your own. Might be worth

Re: [R] Evaluating lazily 'f<-' ?

2021-09-16 Thread Andrew Simmons
when you do 'substitute', it will give you the literal symbol 'x', not really what you wanted, because of the non-standard evaluation. Of course, do whatever you want to make the syntax look the way you want, but I think you're going about this the wrong way. I think the 'which' argument I previously sug

Re: [R] How to remove all rows that have a numeric in the first (or any) column

2021-09-14 Thread Andrew Simmons
I'd like to point out that base R can handle a list as a data frame column, it's just that you have to make the list of class "AsIs". So in your example temp <- list("Hello", 1, 1.1, "bye") data.frame(alpha = 1:4, beta = I(temp)) means that column "beta" will still be a list. On Wed, Sep 15,

Re: [R] Evaluating lazily 'f<-' ?

2021-09-14 Thread Andrew Simmons
c("some names")) x <- `*tmp*` Another example, y <- `names<-`(x, value = c("some names")) now y will be equivalent to x if we did names(x) <- c("some names") except that the first will not update x, it will still have its old names. On Mon, Sep 13, 2021

Re: [R] How to remove all rows that have a numeric in the first (or any) column

2021-09-14 Thread Andrew Simmons
'is.numeric' is a function that returns whether its input is a numeric vector. It looks like what you want to do is VPN_Sheet1 <- VPN_Sheet1[!vapply(VPN_Sheet1$HVA, "is.numeric", NA), ] instead of VPN_Sheet1 <- VPN_Sheet1[!is.numeric(VPN_Sheet1$HVA), ] I hope this helps, and see ?vapply if

Re: [R] Evaluating lazily 'f<-' ?

2021-09-13 Thread Andrew Simmons
ting. > The forced evaluation makes sense for subsetting. > > > On 9/13/2021 9:42 PM, Leonard Mada wrote: > > Hello Andrew, > > > I try now to understand the evaluation of the expression: > > e = expression(r(x) <- 1) > > # parameter named "value" see

Re: [R] Evaluating lazily 'f<-' ?

2021-09-13 Thread Andrew Simmons
lt;- function (x, which) { which <- match.which(which) # more code } some_other_style <- function (x, which) { which <- match.which(which) # more code } I hope this helps. On Mon, Sep 13, 2021 at 12:17 PM Leonard Mada wrote: > Hello Andrew, > > > this could work. I will

Re: [R] Evaluating lazily 'f<-' ?

2021-09-13 Thread Andrew Simmons
I think you're trying to do something like: `padding<-` <- function (x, which, value) { which <- match.arg(which, c("bottom", "left", "top", "right"), several.ok = TRUE) # code to pad to each side here } Then you could use it like df <- data.frame(x=1:5, y = sample(1:5, 5)) padding(df,

Re: [R] Calculate daily means from 5-minute interval data

2021-09-02 Thread Andrew Simmons
You could use 'split' to create a list of data frames, and then apply a function to each to get the means and sds. cols <- "cfs" # add more as necessary S <- split(discharge[cols], format(discharge$sampdate, format = "%Y-%m")) means <- do.call("rbind", lapply(S, colMeans, na.rm = TRUE)) sds

Re: [R] How to globally convert NaN to NA in dataframe?

2021-09-02 Thread Andrew Simmons
ngiu wrote: > Sorry, > still I don't get it: > ``` > > dim(df) > [1] 302 626 > > # clean > > df <- lapply(x, function(xx) { > + xx[is.nan(xx)] <- NA > + xx > + }) > > dim(df) > NULL > ``` > > On Thu, Sep 2, 2021 at 3:47 PM Andrew Sim

Re: [R] How to globally convert NaN to NA in dataframe?

2021-09-02 Thread Andrew Simmons
> List of 1 > $ sd_ef_rash_loc___palm: logi NA > ``` > What am I getting wrong? > Thanks > > On Thu, Sep 2, 2021 at 3:30 PM Andrew Simmons wrote: > > > > Hello, > > > > > > I would use something like: > > > > > > x <-

Re: [R] How to globally convert NaN to NA in dataframe?

2021-09-02 Thread Andrew Simmons
Hello, I would use something like: x <- c(1:5, NaN) |> sample(100, replace = TRUE) |> matrix(10, 10) |> as.data.frame() x[] <- lapply(x, function(xx) { xx[is.nan(xx)] <- NA_real_ xx }) This prevents attributes from being changed in 'x', but accomplishes the same thing as you have

Re: [R] Converting characters back to Date and Time

2021-08-31 Thread Andrew Simmons
Hello, I'm assuming you're reading from an "*.xlsx" file. I'm not sure which package you're using for this scenario, but my preference is 'openxlsx'. If this is the package you're using, you could set argument 'detectDates' to 'TRUE', and then it should read them correctly. FILE <-

Re: [R] Calculate daily means from 5-minute interval data

2021-08-29 Thread Andrew Simmons
Hello, I would suggest something like: date <- seq(as.Date("2020-01-01"), as.Date("2020-12-31"), 1) time <- sprintf("%02d:%02d", rep(0:23, each = 12), seq.int(0, 55, 5)) x <- data.frame( date = rep(date, each = length(time)), time = time ) x$cfs <- stats::rnorm(nrow(x))

Re: [R] Finding if numbers fall within a range

2021-08-28 Thread Andrew Simmons
Hello, I think I've found a solution, but it's not producing the same answer as what you're expecting. I think you might've mixed up row and column a few times, but you should be able to alter the following to your needs. Also, see ?.bincode: EB <- matrix(data = c( 1, 271, 179, 359, 178,

Re: [R] Potential bug/unexpected behaviour in model matrix

2021-08-26 Thread Andrew Simmons
Hello, I'm not so sure this is a bug, it appears to be behaving as intended from the documentation. I would suggest using argument 'physical' from 'setkey' to avoid reordering the rows. Something like: x <- data.table::data.table(V1 = 9:0) y <- data.table::copy(x) data.table::setkey(x, V1,

  1   2   3   4   5   6   7   8   >