r/R_Programming • • Jan 11 '17

Anyone familiar with Flexmix?

2 Upvotes

Hello,

I've run the example code in the flexmix vignette using the NPreg data and notice that they use the regression formula = yn~ x + I(x2). When you plot yn against x, you do notice both a linear and parabolic trend, so this makes sense.

When the flexmix object is refitted using refit() and then summary() is used on the refit, you can see x2 appear as a variable in the regression.

When I attempt to do the same using my own data frame with novel variables:

ex2 <- flexmix(wt ~ totE + I(totE2), data = samp1, k = 2) ex2r<- refit(ex2) summary(ex2r)

Call: flexmix(formula = wt ~ totE + I(totE2), data = samp1, k = 2)

     prior size post>0 ratio

Comp.1 0.275 178 1000 0.178 Comp.2 0.725 822 982 0.837

'log Lik.' -4052.057 (df=9) AIC: 8122.115 BIC: 8166.284

it seems to just ignore the I(totE2). I could understand if I used the incorrect syntax, but no error code pops up. I'd appreciate any help in improving my understanding of flexmix. Thank you!


r/R_Programming • • Jan 03 '17

Brain fart - selecting and separating out particular cases

2 Upvotes

I know I know how to do this, but After the winter vacation (glorious, glorious vacation), my brain is still not working very well.

Data:

c_Eventd_DateLocalc_Result
100m7/10/2003 22:0010.09
100m8/14/2003 22:009.97
100m9/4/2003 22:0010.09
200m9/4/2003 22:0020.04
100m9/12/2003 22:0010.12
200m6/7/2004 22:0020.3
100m8/5/2004 22:0010.06
100m8/21/2004 22:009.85
200m8/25/2004 22:0020.03

Desire: Separate all cases of 100m from all cases of 200m, retaining all other associated variable values in each case.

Question: How?

Sorry its such a noob question, like I said though, brain not work good after 14 days off.


r/R_Programming • • Jan 03 '17

What's the best way to expose R to other languages (e.g. Python)?

2 Upvotes

Hello!

I am working on a RESTful API and I found some great R programming libraries I'd like to use as part of a larger behind the scenes analysis. I have basic R experience, but am stumped on how best to access R from other languages, in this case Python.

Options:

  • rpy2: the docker image is quite large (>1gb), and it is otherwise tricky to set up.

  • Make a command line tool in R and call it as a subprocess? (what would be best practices here?)

  • something else?

I'm trying to deploy my API as part of a containerized web application if that helps. Thank you for any advice!


r/R_Programming • • Dec 06 '16

R assignment Help

2 Upvotes

I'm in a really tough spot and need help ASAP on a project. I am willing to pay for the help and immediacy but I need to know you can get it done as soon as possible. the assignment involves Gene analysis with r packages.


r/R_Programming • • Dec 05 '16

How can I make this code more efficient?

2 Upvotes

Hi guys. Relatively new to R. I've written a batch of code to access a sports database API and pull information from it. I've found myself basically writing the same 5 lines of code over and over again with minor variations, mainly just renaming variables and altering the URL to access different parts of the API.

Since I'm repeating the same code chunk (or very nearly repeating), I have a suspicion that I can rewrite my code to be shorter and more efficient, which would be great because I'm just starting to explore this database, and having to write out 5 or 6 lines of code for every call will take me forever. However, I don't know how to do that. How could I rewrite the following the code in a more efficient manner? Thanks ahead of time for any and all help.

# Speed Skating competitions in a season
speedSkateURL <- "http://demo.api.infostradasports.com/svc/SpeedSkating.svc/json/GetEditionList?Season=20122013&languageCode=2"
speedSkate.raw <- GET(url = speedSkateURL, authenticate(usename, pw))
speedSkate.raw$status_code
speedSkate.raw.content <- rawToChar(speedSkate.raw$content)
speedSkateComps <- fromJSON(speedSkate.raw.content)

# Speed Sktae Phases 2013 Euro Championships.  Phases = individual events?
 speedSkate2013EuroURL <- "http://demo.api.infostradasports.com/svc/SpeedSkating.svc/json/GetPhaseList?editionId=802457&languageCOde=2"
speedSkateEuroRaw <- GET(url = speedSkate2013EuroURL, authenticate(usename, pw))
speedSkateEuroRaw$status_code
speedSkate2013EuroContent <- rawToChar(speedSkateEuroRaw$content)
speedSkate2013Euro <- fromJSON(speedSkate2013EuroContent)

# Speed Skate 2013 Euro Champ 500m results   
speedSkate500EuroURL <- "http://demo.api.infostradasports.com/svc/SpeedSkating.svc/json/GetResult?phaseId=802464&languageCode=2"
speedSkate500EuroRaw <- GET(url = speedSkate500EuroURL, authenticate(usename, pw))
speedSkate500EuroContent <- rawToChar(speedSkate500EuroRaw$content)
speedSkate500Euro <- fromJSON(speedSkate500EuroContent)

PS I apologize for any errors in formatting...having to go through and put spaces in front of eveything is time consuming!

Edit: Also, since I'm still new to writing code, any suggestions for syntactical or sytlistic improvements would be appreciated as well!


r/R_Programming • • Oct 03 '16

Help installing packages in R studio? (Mac)

2 Upvotes

Hey, R newbie here and I can't seem to install packages in R Studio.

I've tried two:

  • xlsx

I type:

install.packages("xlsx")    
library("xlsx")

Output:

 The downloaded binary packages are in
       	/var/folders/9j/_nln83dj4dxdh5pfvfk65j4m0000gn/T//RtmpvRhwmp/downloaded_packages    

> library("xlsx")
JavaVM: requested Java version ((null)) not available. Using Java at "" instead.
JavaVM: Failed to load JVM: /bundle/Libraries/libserver.dylib
JavaVM FATAL: Failed to load the jvm library.
Error : .onLoad failed in loadNamespace() for 'xlsx', details:
  call: .jinit()
  error: JNI_GetCreatedJavaVMs returned -1

Error: package or namespace load failed for ‘xlsx’    
  • stringi Commands are the same as above. Output:

      The downloaded source packages are in
       ‘/private/var/folders/9j/_nln83dj4dxdh5pfvfk65j4m0000gn/T/RtmpvRhwmp/downloaded_packages’
      > library("stringi")
      Error in library.dynam(lib, package, package.lib) : 
        shared object ‘stringi.so’ not found
      Error: package or namespace load failed for ‘stringi’    

I realise these are two different outputs, which is unhelpful. I've tried playing around both in R directly and R studio and I've tried different mirrors.

Would be grateful for help.


r/R_Programming • • Sep 13 '16

Learning R, quick question

2 Upvotes

Im learning R and i know the one mistake i made with python, is that i learned it in its default command shell. I didnt know ipython notebook existed.

im running R in interactive mode out and its very similar to pythons defualt shell. Is there a better method to writing your R code? it seems like doing this for large data projects would be quite annoying .

if i knew of ipyhtohon, it would of cut the time down for me to learn python dramatically


r/R_Programming • • Sep 12 '16

R Web Scraping Instructions

2 Upvotes

Hello!

I am relatively new to R programming, and am curious if there are any easy to follow tutorials on how to web scrape.

Any assistance is greatly appreciated!


r/R_Programming • • Aug 15 '16

Sample equal amount?

2 Upvotes

Say you have 15 names in a df. You want to add a number 0, 1 or 2 to each person randomly. And you want each group (0,1,2) to have equal size.

Stuck on the last part with equal size..


r/R_Programming • • Jul 25 '16

Nested list to df?

2 Upvotes

I have a list that looks like below. Problem is there is a nested list ($toLoc) inside.

[[1]]
[[1]]$timeAtLoc
[1] "2016-07-29T00:20:00"
[[1]]$id
[1] "83"
[[1]]$toLoc
[[1]]$toLoc[[1]]
[1] "LA"
[[1]]$toLoc[[2]]
[1] "NY"
[[1]]$num
[1] "3"

I think I want to get it all in a (long) df looking something like:

id timeAtLoc            toLoc
83 2016-07-26T00:26:00  LA
83 2016-07-26T00:26:00  NY

Any advice?

Thanks


r/R_Programming • • Jul 14 '16

What is the difference between factors and characters when using Linear regression?

2 Upvotes

Hello, main question is in the header. I am doing a multiple linear regression, and wanted to know if it is better to list random effects(subjects) as a factor or character. I ran models with both, and the output is different.


r/R_Programming • • Jun 08 '16

New to R, need a little help with for loop formatting.

2 Upvotes

Hello im trying to write a simple script in rstudios, and I've work with other similar languages, so im not to familiar with the formatting in r. I have written something similar to...

m1 <- cbind(a1,a2,a3,a4) ##a1 to a4 are vectors with integers.

for (i in seq(along=m1[1,])){ ## I believe (i in 1:4) would provide the same outcome.

v1 <- rep(0,length(m1[1,]))

v1[i] <- length(m1[,i])

v2 <- rep(0,length(m1[1,]))

v2[i] <- var(m1[,i])

.

.

.

}

cbind(v1,v2,...)

But my output matrix consists of only zeros until the very last row which have the correct values. So my question is why doesn't the script putt any values in the first dimensions in my v1,v2,...,vn vectors.

Thank you for your time.


r/R_Programming • • May 08 '16

High School Newbie

2 Upvotes

Hey everyone, I have to learn how to use R for a bioinformatics research internship that I'm doing but I'm completely lost and have no prior experience.

What are some resources that helped you tons? xoxo thanks


r/R_Programming • • Apr 29 '16

Monte Carlo simulation to explore performance of two Estimators of Variance

2 Upvotes

Wondering if anyone out there could shed some light on these statistical ideas? Google is failing me!

Trying to understand:

S2 = Sum(Xi - x)2 /n-1

S2 p = Sum(Xi - x)2 /n (Note: S2 p is also known as σ2 right?)

so MSE(S2 ) = 2σ4 /n-1 and MSE(S2 p) = (2n-1)σ4 /n2

Is this all correct so far??

What I need to do is simulate a set of randomly generated numbers then use these to calculate the MSE for each estimator and hence come the the conclusion that one of them is better (Should be σ2 according to google). But when it comes to evaluating each of the MSEs I think I am doing it wrong!! So I am just stuck on how to evaluate each of the MSE for S2 and σ2. Does S2 get inserted into each of the MSE formulas? (bold bits) At the moment σ2 is giving me a HUGE MSE(σ2) =235.5 and S2 only small MSE(S2)=5.8 when n=10..

As n gets large my σ2 and hence MSE(σ2) get negative!? feels very wrong!

Hopefully someone out there can shed some light! Sorry if this is the wrong subreddit...

Cheers!!


r/R_Programming • • Mar 26 '16

R geosphere package: find the point that is a given distance away from a great circle

2 Upvotes

Suppose we know the longitudes/latitudes of two points p1 (-104.673178,39.861656), p2 (-87.904842, 41.978603), we want to find the coordinates of P3 which is 100Km away from the great circle determined by p1 and p2. It is also required that the closest point in the great circle to p3 is p2.

Here is my way to find p3:

First use finalBearing function to find the final bearing of the great circle at p2.

fbearing=finalBearing(p1,p2,sphere=TRUE) 

fbearing=139.4564

Because the closest point in the great circle to p3 is p2, angle p3-p2-p1 should equal to 90 degree (is it true?). We can then use destPoint to find p3

p3=destPoint(p2,-(180-fbearing)-90,100*1000,r=6378137,sphere=TRUE)

p3=(-105.555,39.27437)

However, when I use dist2gc to calculate the distance between a point and a great circle

dist2gc(p1, p2, p3, r=R)

The answer is -100106.4, not -100000.

Is my way to find p3 wrong ? Or is 106 meter is acceptable error?

The link of geosphere package: https://cran.r-project.org/web/packages/geosphere/geosphere.pdf


r/R_Programming • • Mar 20 '16

Finding the Right Conditional Statement for my new Column?

2 Upvotes

I am having trouble thinking of the best way to code conditions for very specific counts in my data table. Are there any specific websites that are good resources for R conditional statements? Is my best bet just googling what I want to do?


r/R_Programming • • Mar 17 '16

computer vision using R

2 Upvotes

Currently am learning R programming and this occurred to me how computer vision related problems can be done using R. What are the packages available for computer vision and image processing?


r/R_Programming • • Mar 12 '16

as.numeric returns 1 & 2 instead of 0 &1

2 Upvotes

I have a column of data that is a factor, tested and untested. When I do any analysis, and use as.numeric uses 1 for tested and 2 for untested. I would like it to be 0 and 1 instead. Is there a way to do this?


r/R_Programming • • Mar 01 '16

Statistical Arbitrage Strategy in R [EPAT Project]

Thumbnail
quantinsti.com
2 Upvotes

r/R_Programming • • Feb 16 '16

Atom for R?

2 Upvotes

Hi,

Getting into R programming for analysing stock market/economic data, and struggling with which text editor/IDE to use, bearing in mind that once I'm comfortable with R I'm looking to move onto python and some JS and CSS and don't want to be repeatedly learning new tools/environments i.e. would like to stick to one editor.

Love the features and future possibilities of atom, but R support seems fairly limited atm. I've installed the language-r package and lintr (which is spitting out the error "Error: 'R' is not recognized as an internal or external command, operable program or batch file." if anyone knows how to fix this it would be highly appreciated), though i believe in order to run the code you have to copy it over to the Rterminal to run it/interact.

should i stick with this workflow and wait for a package to be released to interact with the terminal from within atom, or move over to emacs + ESS or something similar? open to suggestions, thanks everyone !

Dan


r/R_Programming • • Feb 10 '16

R Error Message

2 Upvotes

Hi everybody, I am attempting to use the Single Index model to estimate alpha beta and sigma2_ei for 3 stocks and the TSX. Here is my current R code

Importing the Data

setwd("~/Desktop/R Data Sets") Ass2Data1 <- read.csv("~/Desktop/R Data Sets/Ass2DataSheet1.csv") View(Ass2Data1)

Transforming the data into matrix form

b <- as.matrix(Ass2Data1)

Generating Initial Vectors and Matrices

x <- rep(0,60) xx <- matrix(x, ncol=4, nrow=3)

stock <- rep(0,3) alpha <- rep(0,3) beta <- rep(0,3) mse <- rep(0,3) Rbar <- rep(0,3) Ratio <- rep(0,3)

col1 <- rep(0,3) col2 <- rep(0,3) col3 <- rep(0,3) col4 <- rep(0,3) col5 <- rep(0,3)

Regressing each stock on the index and recording results

for(i in 1:3){

alpha[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,1] ~ Ass2Data1[,4]$coefficients[1])

beta[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,2] ~ Ass2Data1[,4]$coefficients[2])

Rbar[i] <- alpha[i]+beta[i]*mean(b[,4])

mse[i] <-sum(lm(data=Ass2Data1,formula=Ass2Data1[,i] ~ Ass2Data1[,4])$residuals2)/(nrow(b)-2)

Ratio[i] <- (Rbar[i]/beta[i])

stock[i] <- i }

xx <- (cbind(stock,alpha,beta,Rbar,mse,Ratio))

However I keep getting the following error messages: Error in Ass2Data1[, 4]$coefficients : $ operator is invalid for atomic vectors

and

Error in beta[i] * mean(b[, 4]) : non-numeric argument to binary operator


If anybody could point me in the right direction with respect to what I'm doing wrong here it would be greatly appreciated.


r/R_Programming • • Feb 08 '16

Back in November, for a university class, I made a small script that uses the 'RedditExtractoR' package and makes some basic analysis. I decided to share, hope you can find it useful!

Thumbnail
github.com
2 Upvotes

r/R_Programming • • Jan 21 '16

Looking for a R programmer for London location

2 Upvotes

Hi All, I have a job opening for a finance client based in London. They are looking for someone with Risk or Finance background (preferred) and with 5-7 years of experience with

  • good understanding of financial models.

  • design, build, maintain, test R Programs

  • experience in data manipulation, time series, probability distribution and SQL.

How do I find a R-programmer. Linkedln so far has not been helpful. Try searching for R :) Any inputs will be very helpful or anyone looking for a permanent role, please say hi.


r/R_Programming • • Jan 13 '16

Best MOOC for learning R

2 Upvotes

Hey, my brother is an econ student out in the land of Ivy leagues and says I need to learn R. I'm wondering what MOOCs there are for this. I see the one offered by Johns Hopkins @ Coursera, as well as one offered by UT Austin @ EdX.

Just wondering which one y'all have tried and if one is particularly better than the other. Or if there are yet other options to go for. I do like the idea of getting some sort of certification.

Thanks, and I am excited to get learning!


r/R_Programming • • Nov 10 '15

Issue loading packages while running R script using R CMD BATCH in command prompt.

2 Upvotes

Hello,

I am trying to run an R script that is executed using an "R CMD BATCH" command in the command prompt. I first tried using the "install.packages" command at the beginning of my script but it failed because it could not select a CRAN mirror. I changed this to install.packages('Package Name', repos='http://cran.us.r-project.org') and then require(Package Name). I am already tried library(Package Name). Sometimes my code works fine but other times my Rout file provides an error such as this:

Warning message:
In library(package, lib.loc = lib.loc character.only=TRUE logical.return=TRUE, : there is no package called 'plyr')

It also tends to fail with the foreign and reshape packages. How can I install packages via R script so it does no fail? My current code appears below:

install.packages('reshape', repos='http://cran.us.r-project.org') 
install.packages('foreign', repos='http://cran.us.r-project.org')
install.packages('plyr', repos='http://cran.us.r-project.org')
install.packages('dplyr', repos='http://cran.us.r-project.org')
install.packages('doBy', repos='http://cran.us.r-project.org')

require(reshape)
require(foreign)
require(plyr)
require(doBy)
require(dplyr)

Thanks!