r/R_Programming • • Sep 16 '16

Is there any linked list R implementation?

1 Upvotes

I am new to R and need a fast growing list...


r/R_Programming • • Jul 23 '16

Hours and minutes on axis with correct scale?

1 Upvotes

I am trying to plot (ggplot) time in hours and minutes (for instance 6.11) on the x axis. Of course the scale is wrong, 6.50 is between 6 and 7 when it should be very close to 7. Guess its base 10 vs base 60?

Found a little bit about lubridate, ggplot and scale_x_datetime() but not getting anywhere.

Thanks


r/R_Programming • • Jul 18 '16

Read Table versus Read CSV

1 Upvotes

Hi all, I was hoping that someone could help with a question. I am trying to figure out the difference between Read.Table and Read.CSV in R. The reason I ask is because a lot of times code I read online uses the Read.Table command. When I try to use the Read.Table command in R (as opposed to Read.CSV) it does not work). I read that Read.Table is for .txt files and when I used an online .csv to .txt converter, R would read the data. The only reason I care to use read.table is because I often see code that I want to replicate use read.table rather than read.csv. Any input/help is much appreciated.


r/R_Programming • • Jul 08 '16

Wide to long?

1 Upvotes

My head does not want to grasp the wide vs long variables.. I have a df containing:

"2010"	"2011"	"2012"	"2013"	"2014"	"2015"
5007	4626		4563		4593		4677		5069

How do I make it 6 observations of 2 variables instead of the below?

> str(x)
'data.frame':	1 obs. of  6 variables:

r/R_Programming • • Jun 22 '16

Help with creating a function

1 Upvotes

I am trying to learn R and I am still very confused and can't seem to find anything to help me with my task. I have been asked to create a function that is able to get the sum of multiple arguments. In other words instead of getting the sum of three arguments, which requires 3 numbers. How can I create a function that can get the sum of an infinite amount of numbers?

Also, on another note does anyone have any good sites or videos for learning R?

Thanks for any help in advanced.


r/R_Programming • • Jun 13 '16

Using nested (s)apply to run a function with data frames as inputs

1 Upvotes

I'm going to walk through what I'm doing and hopefully someone can offer some insight.

I've got a folder of csv files, which I read in as a bunch of data frames. I've got a function which takes in 2 data frames and some arguments to filter out some data from the frames. The result is a single number. I want to run this function over every possible combination of 2 data frames and combine them into a matrix, with rows and columns for every data frame (every file), and a value for every combination. It's trivial to do with a couple for loops, but I can't figure out how to avoid both of them.

What I found I can do is avoid 1 for loop, but not both. What I'm doing right now is making a list of all the data frame names. Using get() and mget(), I can pull a dataframe, or multiple data frames, and use them. That means I can iterate over the list. So far, I've got this:

for (R in 1:Nfiles) {
    frame1 = get(Framelist[R])
    frames2 = mget(Framelist[1:R])
    RowOutput = sapply(frames2, myfunction, ...)
    MatrixVals[R,] = RowVals
}

That's psudocode (a little), but I've basically got it so that I can use the for loop to go through each row, and then calculate the matrix values in that row (I actually just do the first half of the row and take advantage of symmetry later) using the sapply(). It's faster than 2 for loops, but not by much and I need it to go faster. I attempted using nested sapply() loops in this manner:

Matrix = sapply(mget(Framelist), function(f1) {
    sapply(mget(Framelist), function(f2) {
        myfunction(f1, f2, ... )
    )}
)}

I think I'm on the right track, but I keep getting an error that the "value for 'framename' not found". I can't figure out why this would be because I look at the variables I have using ls(all.names=T) and the framename clearly exists. Is this just a formatting or syntax issue, or can R not do what I want?


r/R_Programming • • Jun 02 '16

How do I change the keyboard language in R?

1 Upvotes

My regular computer keyboard language is working fine, but in R, when I press the shift button, some random characters are used.

For example:

Regular keyboard gives me: ^ { } : " < > [ ] ; ' , . /

When scripting R, I respectively get: ? ¨Ç : È ' "" É ^ ç ; è , . é


r/R_Programming • • May 28 '16

Need help: Recursive function that operates on its own preceding output

1 Upvotes

I have the price for a particular baseline year (in this case for 1993), and the multiplication factor for all the years. Using these known multiplication factor, I want to compute (project) price for all years succeeding and preceding the baseline year.

Here is the input data:

Year	City	MultiplicationFactor	Price_BaselineYear
1990	New York	      NA    	    NA
1991	New York	      0.9    	    NA
1992	New York	      2.0    	    NA
1993	New York	      0.8    	    100
1994	New York	      0.6    	    NA
1995	New York	      0.8    	    NA
1996	New York	      2.0    	    NA
1990	Boston	           NA    	    NA
1991	Boston	           1.6    	    NA
1992	Boston	           1.25    	    NA
1993	Boston	           0.5    	    200
1994	Boston	           1.75    	    NA
1995	Boston	           2.5    	    NA
1996	Boston	           0.5    	    NA

The code to construct the input Data:

myData<-structure(list(Year = c(1990L, 1991L, 1992L, 1993L, 1994L, 1995L,1996L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L), City = structure(c(2L,2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Boston","New York"), class = "factor"), MultiplicationFactor = c(NA,0.9, 2, 0.8, 0.6, 0.8, 2, NA, 1.6, 1.25, 0.5, 1.75, 2.5, 0.5),`Price(BaselineYear)` = c(NA, NA, NA, 100L, NA, NA, NA, NA,NA, NA, 200L, NA, NA, NA)), .Names = c("Year", "City", "MultiplicationFactor","Price_BaselineYear"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L))

The output I desire (the last column, Price_AllYears):

Year	City	MultiplicationFactor	Price_BaselineYear	Price_AllYears
1990	New York	NA					NA					69.4
1991	New York	0.9					NA					62.5
1992	New York	2.0					NA					125.0
1993	New York	0.8					100					100.0
1994	New York	0.6					NA					60.0
1995	New York	0.8					NA					48.0
1996	New York	2.0					NA					96.0
1990	Boston		NA					NA					200.0
1991	Boston		1.6					NA					320.0
1992	Boston		1.25				NA					400.0
1993	Boston		0.5					200					200.0
1994	Boston		1.75				NA					350.0
1995	Boston		2.5					NA					875.0
1996	Boston		0.5					NA					437.5

Here is what I have so far:

myData %>%
  group_by(City) %>%
  arrange(Year) %>%
  mutate(Price_AllYears = ifelse(Year < Year[which(!is.na(Price_BaselineYear))], 
                        lead(Price_AllYears) / lead(MultiplicationFactor),
                        ifelse(Year > Year[which(!is.na(Price_BaselineYear))],
                               lag(Price_AllYears) * MultiplicationFactor,
                               Price_BaselineYear)))%>%
  ungroup() %>% 
  arrange(City)

This is the error I get:

Error: object 'Price_AllYears' not found

Here is the method I would use if I had to use Excel:

	A		B		C						D					E
1	Year	City	MultiplicationFactor	Price_BaselineYear	Price_AllYears
2	1990	New York	NA					NA					E3/C3
3	1991	New York	0.9					NA					E4/C4
4	1992	New York	2.0					NA					E5/C5
5	1993	New York	0.8					100					D5
6	1994	New York	0.6					NA					E5*C6
7	1995	New York	0.8					NA					E6*C7
8	1996	New York	2.0					NA					E7*C8
9	1990	Boston		NA					NA					E10/C10
10	1991	Boston		1.6					NA					E11/C11
11	1992	Boston		1.25				NA					E12/C12
12	1993	Boston		0.5					200					D12
13	1994	Boston		1.75				NA					E12*C13
14	1995	Boston		2.5					NA					E13*C14
15	1996	Boston		0.5					NA					E14*C15

r/R_Programming • • May 26 '16

Getting a hashtable from a labeled matrix

1 Upvotes

I have a matrix originalmat which has its dimnames() labeled, and I want to be able to quickly look up the column index of a given label. How do I do that efficiently? This solution works but is very slow on large matrices:

mapping = list();

for (i in 1:length(dimnames(originalmat)[[1]])) {

    mapping[[dimnames(originalmat)[[1]][i]]] = i;

}

r/R_Programming • • May 24 '16

Beginner R problem: Plotting x-values that depend on two different columns of the dataset

1 Upvotes

Say I have the following data (tab delimited file):

1   5   50
1   7   25
1   11  77
...
2   3   33
2   4   67
2   9   29

and so on.

Column 1 represent different sections, and each section has their own ranges. I would like to plot the sections next to each other along one x-axis (of course when a section changes I would like that to be labelled). Someone else on stackoverflow posted the exact same question. But there was no answer.


r/R_Programming • • May 23 '16

R comments 2 colors?

1 Upvotes

Hi I was wondering if there is a way in R to have 2 different colors for comments in an R script. I was sent some code that already has comments and I want to add my own and make it obvious (changes not tracked in Github or anything else)


r/R_Programming • • May 17 '16

R ease for importing bulk data

1 Upvotes

Is it relatively quick and clear in R on how to import large sets of data in a variety of formats (csv, json, xml) ? I can see dyplr and tutorial and all looks easy. What if though the file was a weekly file and suddenly you had 52 files to import clean and use?

Dpylr introduction https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html


r/R_Programming • • May 08 '16

Help with converting a factor variable to a date? I'm so stuck. :(

1 Upvotes

Hi Everyone, I'd really appreciate your help if you have any clues for me -- I'm trying to convert a factor variable within a .csv to a date, I've used the following: ArrivalDate = as.Date(strptime(MyData$ArrivalDate.Date, "%d/%m/%y")

I've googled everything I can think of, but I don't know what I'm doing wrong! When I asked it for a summary(ArrivalDate) it just comes up with N/A's all round. :(

On a side note, I came to reddit looking for fellow R-er's, I was disappointed we couldn't get /r/r :D


r/R_Programming • • May 04 '16

R Data Frame and basic functions

Thumbnail howtoprogram.xyz
1 Upvotes

r/R_Programming • • May 03 '16

Plotting Ranger Random Forests

1 Upvotes

Is there a way to plot the random forest model/tree from the ranger package?


r/R_Programming • • Apr 01 '16

3D Spatial Interpolation help?

1 Upvotes

Could anyone throw me some packages or tutorials that might come in handy when trying to create a three dimensional spatial interpolation plot? Basically I have groundwater data for the depth of an aquifer but only at certain points and want to spatially interpolate the data to get a better picture of the entire aquifer's depth over the area of land. I have done this in a simple two dimensional plot of just latitude and longitude but I feel like there's probably a way to create a 3D picture using the depth measurements in my dataset. (If this isn't clear I can try to clarify more, I'm sorry I'm very new to R and programming in general so I don't know how to articulate what I'm trying to say very well)

THANK YOU IN ADVANCE


r/R_Programming • • Mar 31 '16

Can't insert dates as column names

1 Upvotes

I have data of periods of time and I'm making sort of a pivot table. I don't have information on some days and wanted the values for that days to be zero. Still, I have to add those days to the table and I'm not being able to do it. Here's a screenshot of what's happening: http://imgur.com/YHnatxS

I have no idea on how to solve this. Any suggestion?


r/R_Programming • • Mar 26 '16

New to R - need help with turning graphs into dataframes in KEGGgraph

1 Upvotes

Hi everyone,

I'm learning R for the purpose of a research project with a professor at my university. I'm trying to pull a bunch of biological data from KEGG in order to run a python script on it - this is where R comes in. R has a useful package for the data collection called KEGGgraph. So I've been able to pull all of the data as XML's, and now I'm trying to turn the XML's into useful data.

The built in method that KEGGgraph uses parses the XML into a NELgraph object, and then converts the graph object into a dataframe. The problem arises when I try to loop over all of my XMLs and do this to each one. My code looks like, essentially:

for(i in 1:133) 
    dataframes[i] = parseKGML2DataFrame(files[i])

When I run the script, I get a "replacement has length zero" error on every single iteration of the loop.

So, I'm hoping someone can explain to me where this problem might be coming from, or method of parsing all the files to dataframes in a better way (better than looping).


r/R_Programming • • Mar 23 '16

Anyone here used Random Forest Walk in R before?

1 Upvotes

Hi guys,

I'm trying to use Random Forest Walk for the first time on a dataset with 120 masked variables. I understand the concept but absolutely no idea about how to do it in R and how to read the results.

I've tried looking for many online resources but couldn't find a concise step by step guide.

Can any of you guys who've used it before explain how I can do it and how to read the outputs?


r/R_Programming • • Mar 20 '16

Curly Brackets within functions

1 Upvotes

I’ve come across functions with the following format x({…}) instead of just x( ). As an example:

suppressWarnings({ yahoo_answer <- tryCatch({ getSymbols(ticker, src = "yahoo") }, error = function(err) { NA }) })

Here suppressWarnings is a function, but inside of it is code enclosed by curly brackets.

Here’s another example:

results <- read.table("data/Ticker_List.csv", stringsAsFactors = FALSE) %>% set_colnames("ticker") %>% rowwise() %>% do({ .ticker <- .$ticker processTicker(ticker = .ticker, avg_days = 63, percentile = 0.95) }) %>% ungroup()

The internals of the do function are enclosed in curly brackets.

What is the purpose of the curly brackets within functions. I have an idea of how and why it works here in particular, but I don’t know enough to generalize this and put this into my own code. Can anyone help me understand how and when you would use this kind of structure.

Thanks!


r/R_Programming • • Mar 09 '16

Try to convert to factor but typeof() still says character?

1 Upvotes

I want to try anova and need to convert a column to factor. But it does not seem to work?

x1[,'tr'] <- as.factor(x1[,'tr']) typeof(x1[,'tr']) [1] "character"


r/R_Programming • • Mar 07 '16

Lots of error codes, trying do perform RDA

1 Upvotes

What I have written is:

MP_bac<-read.csv(choose.files())
MP_meta<-read.csv(choose.files())
MP_bac_matrix<- as.matrix (MP_bac)
MP_meta_matrix<- as.matrix (MP_meta)
MP_bac_frame<-as.data.frame(MP_bac)
MP_meta_frame<-as.data.frame(MP_meta)

Then, briefly, went into direct the console part of RStudio instead of the Script part to convert from integer to numeric form via:

> MP_bac_numeric<-transform(MP_bac_frame, "integer" = as.numeric("integer"))
Warning message:
In eval(expr, envir, enclos) : NAs introduced by coercion
> MP_meta_numeric<-transform(MP_meta_frame, "integer"= as.numeric("integer"))
Warning message:
In eval(expr, envir, enclos) : NAs introduced by coercion

Where I thought a few coerced NAs should be fine since we've got na.action=na.omit coming up.

Then:

x<-MP_bac_numeric
y<-MP_meta_numeric

## Default S3 method:
rda(x, y, scale=F, na.rm=TRUE, na.action=na.omit)

Which gave the result:

Error in svd(Xbar, nu = 0, nv = 0) : infinite or missing values in 'x'

Which I have no idea what it means. Googling around, I found the site here that I know is trying to help, but doesn't really explain what's wrong very well to someone super new to this language (and programming in general).

I've gone through and eliminated all non-numeric data from the files I'm using. I've made sure the two files in use have the same setup row-and-column wise. I've converted to data frames, to matrices, to csv, back and forth. I have no idea if it's a wrong file type or what.

Any help would be greatly appreciated.


r/R_Programming • • Mar 05 '16

Help with a for loop

1 Upvotes

Hey there i am having trouble understanding why my loop isn't working and I am looking for some help.

foundyear = startup_data$founded_year 

for(x in 1:50){
 if(foundyear[x] > 2009){
    print('Late Stage')}
  else if(foundyear[x] < 2009){
    print('Early Stage')}
  else if(is.na(foundyear[x])){
    print('data is not available')}
  else print('error')
}

Basically I am trying to look at the first 50 values in this column of data and see if it's before or after 2009 or NA. I get an error saying missing value where TRUE/FALSE needed.

To me, logically, this makes sense, but it's not working so I guess it isn't right. Any tips?


r/R_Programming • • Mar 02 '16

Need help with writing an R loop

1 Upvotes

I'm new to R, and programming in general and I have absolutely zero experience writing loops. I have a basic understanding of the process but the loop I think I need is a bit more complicated so I'm unsure of how to write it (or if I even need a loop at all?) Basically I want to: -Import multiple data sets that all have the same name except ending in the year -Add a column to each data set that is filled with the value of the year -Remove all of the columns I don't want

I know how to do each step individually, but it would save me a lot of time because I have ~25 data sets I want to do this to.

My first attempt at the loop was only the importing step and taking out the columns (below) but I think it makes more sense to add the Year column first before removing any columns.

Code:

my_files<-list.files(pattern="water.data.*")
my_data<-list()
for (i in seq_along(my_files)){
my_data[[i]]<- read.csv(file=my_files[i])
}

keeps<-c("NAME","LONGITUDE","LATITUDE","YEAR","SIZE")
lapply(my_data, function(x){
  x[keeps]
})

Basically I'd just like an explanation of how to do this, and then maybe I could figure it out from there. Thank you so much in advance for even just reading this!!


r/R_Programming • • Feb 29 '16

Difference between () and [] in R programming language

1 Upvotes

when to use [] and () in R language?