I've got a dataframe that includes columns like the one on the right here:

```
lengthArray speed_max
1 4 24, 18, 24, 18
2 10 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
3 4 -999, -999, -999, -999
4 2 -999, -999
5 2 18, 18
6 1 -999
```

For these columns, I've written a function to extract the mean, median, max, or min from the array for each row of the dataframe, but I have a feeling this could be done much faster. Here's what I've got:

```
get_scalar <- function(name, to_return = 1)
{
vec_list = mydata[[name]]
alt_vector = vector(mode = "numeric", length = length(alt_max))
i = 1
# depending on what user wants, return max, min, mean or median
# for each array one per row
if(to_return == 0){
for(entry in alt_max){
alt_vector[i] = max(which(alt_max[i][[1]] != -999))
i = i + 1
}
}else if (to_return==1){
for(entry in alt_max){
alt_vector[i] = min(which(alt_max[i][[1]] != -999))
i = i + 1
}
}
...
#and repeated for two other cases
...
#then finally return the results as numeric vector
alt_vector = as.numeric(alt_vector)
}
```

The expected/desired output of this function is a numeric vector, with each row corresponding to the desired measurement for each array's row in the dataframe. So for example if I run `get_scalar("speed_max", to_return = 0)`

I would expect a numeric vector returned with the first rows being `(24, 2, NA....)`

based on the data I pasted above because max of the first row's "speed_max" array is 24 and max of the second row's "speed_max" array is 2 and the 3rd row does not contain any relevant data (-999 means omit).

I haven't been able to find a way to write this with sapply to access the first member of the list for each cell. For example the following syntax errors out:

```
> gg = max(mydata[[speed_max]][[1]])
Error in (function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, :
object 'speed_max' not found
```

And if I try an sapply rewrite like so, I can't seem to access the individual arrays per row. For example this function just prints out many 0's:

```
get_scalar_sapply <- function(name, to_return = 1)
{
vec_list = mydata[[name]]
alt_vector = vector(mode = "numeric", length = length(alt_max))
if(to_return == 1){
#alt_vector =sapply(alt_vector, function(x) max(which(x[[1]] != -999)))
alt_vector = sapply(alt_vector, function(x) print(x[[1]]))
}
alt_vector = as.numeric(alt_vector)
}
```

```
> dput(head(mydata))
structure(list(endo = c(20216392L, 20167990L, 20211929L, 20214641L,
20206551L, 20178293L), lengthArray = c(4L, 10L, 4L, 2L, 2L, 1L
), sport = list(c(24, 18, 24, 18), c("2", "2", "2", "2", "2",
"2", "2", "2", "2", "2"), c("-999", "-999", "-999", "-999"),
c("-999", "-999"), c("18", "18"), "-999"), local_start_time = list(
c(NA_real_, NA_real_, NA_real_, NA_real_), c("u'2015-05-03T17:14:13.000Z'",
"u'2015-05-03T17:13:22.000Z'", "u'2015-05-03T17:14:13.000Z'",
"u'2015-05-03T17:13:22.000Z'", "u'2015-05-03T17:14:13.000Z'",
"u'2015-05-03T17:13:22.000Z'", "u'2015-05-03T17:14:13.000Z'",
"u'2015-05-03T17:13:22.000Z'", "u'2015-05-03T17:14:13.000Z'",
"u'2015-05-03T17:13:22.000Z'"), c("u'2015-02-25T10:02:10.000Z'",
"u'2015-02-02T22:37:34.000Z'", "u'2015-02-25T10:02:10.000Z'",
"u'2015-02-02T22:37:34.000Z'"), c("u'2015-02-02T18:28:23.000Z'",
"u'2015-02-02T18:28:23.000Z'"), c("u'2015-02-02T10:42:27.000Z'",
"u'2015-02-02T10:42:27.000Z'"), "u'2015-01-31T10:35:54.000Z'"),
distance = list(c(-999, 1.32598698139191, -999, 1.32598698139191
), c("-999", "-999", "-999", "-999", "-999", "-999", "-999",
"-999", "-999", "-999"), c("15.499165534973145", "-999",
"15.499165534973145", "-999"), c("6.071850776672363", "6.071850776672363"
), c("-999", "-999"), "-999"), duration = list(c(4, 1103,
4, 1103), c("8.0", "15.0", "8.0", "15.0", "8.0", "15.0",
"8.0", "15.0", "8.0", "15.0"), c("19492.0", "56.0", "19492.0",
"56.0"), c("1936.0", "1936.0"), c("3.0", "3.0"), "4083.49"),
speed_avg = list(c(-999, 4.32779069175962, -999, 4.32779069175962
), c("-999", "-999", "-999", "-999", "-999", "-999", "-999",
"-999", "-999", "-999"), c("2.862558789549729", "-999", "2.862558789549729",
"-999"), c("11.290631609514724", "11.290631609514724"), c("-999",
"-999"), "-999"), altitude_max = list(c(-999, 366, -999,
366), c("-999", "-999", "-999", "-999", "-999", "-999", "-999",
"-999", "-999", "-999"), c("335.5", "-999", "335.5", "-999"
), c("520.0", "520.0"), c("624.0", "624.0"), "-999"), altitude_min = list(
c(-999, 223, -999, 223), c("-999", "-999", "-999", "-999",
"-999", "-999", "-999", "-999", "-999", "-999"), c("-156.0",
"-999", "-156.0", "-999"), c("453.0", "453.0"), c("624.0",
"624.0"), "-999"), speed_max = list(c(-999, 5.01253,
-999, 5.01253), c("-999", "-999", "-999", "-999", "-999",
"-999", "-999", "-999", "-999", "-999"), c("66.8202", "-999",
"66.8202", "-999"), c("19.8268", "19.8268"), c("-999", "-999"
), "-999"), ascent = list(c(-999, 140, -999, 140), c("-999",
"-999", "-999", "-999", "-999", "-999", "-999", "-999", "-999",
"-999"), c("-999", "-999", "-999", "-999"), c("173.0", "173.0"
), c("-999", "-999"), "-999"), descent = list(c(-999, 272,
-999, 272), c("-999", "-999", "-999", "-999", "-999", "-999",
"-999", "-999", "-999", "-999"), c("-999", "-999", "-999",
"-999"), c("174.0", "174.0"), c("-999", "-999"), "-999"),
title = list(c(-999, -999, -999, -999), c("-999", "-999",
"-999", "-999", "-999", "-999", "-999", "-999", "-999", "-999"
), c("-999", "-999", "-999", "-999"), c("-999", "-999"),
c("-999", "-999"), "-999"), num_runs = c(0L, 0L, 0L,
0L, 0L, 0L), percent_runs = c(0, 0, 0, 0, 0, 0)), .Names = c("endo",
"lengthArray", "sport", "local_start_time", "distance", "duration",
"speed_avg", "altitude_max", "altitude_min", "speed_max", "ascent",
"descent", "title", "num_runs", "percent_runs"), row.names = c(NA,
6L), class = "data.frame")
```

Answer:

It looks like you're trying to grab summary functions from each entry in a list, ignoring the elements set to -999. You can do this with something like:

```
get_scalar <- function(name, FUN=max) {
sapply(mydata[,name], function(x) if(all(x == -999)) NA else FUN(as.numeric(x[x != -999])))
}
```

Note that I've changed your function slightly by passing an actual function to apply to each list element instead of a numeric code corresponding to a function. This makes your function much more flexible because it can now easily take any processing function.

Let's look at a sample from the provided `mydata`

list:

```
# Look at the list:
mydata$speed_max
# [[1]]
# [1] -999.00000 5.01253 -999.00000 5.01253
#
# [[2]]
# [1] "-999" "-999" "-999" "-999" "-999" "-999" "-999" "-999" "-999" "-999"
#
# [[3]]
# [1] "66.8202" "-999" "66.8202" "-999"
#
# [[4]]
# [1] "19.8268" "19.8268"
#
# [[5]]
# [1] "-999" "-999"
#
# [[6]]
# [1] "-999"
# Minimum element in each row
get_scalar("speed_max", min)
# [1] 5.01253 NA 66.82020 19.82680 NA NA
# Number set (NA if none)
get_scalar("speed_max", length)
# [1] 2 NA 2 2 NA NA
```

r,data.table,stata,code-translation

Just came across a .do file that I need to translate into R because I don't have a Stata license; my Stata is rusty, so can someone confirm that the code is doing what I think it is? Here's the Stata code: collapse (min) MinPctCollected = PctCollected /// (mean) AvgPctCollected...

python,python-2.7,pandas,dataframes

I have a dataframe of data that I am trying to append to another dataframe. I have tried various ways with .append() and there has been no successful way. When I print the data from iterrows. I provide 2 possible ways I tried to solve the issue below, one creates...

r,subset

I have the following data frame which I imported into R using read.table() (I incorporated read.table() within read_data() which is a function I created that also throw messages in case the file name is not written appropriately): > raw_data <- read_data("n44.txt") [1] #### Reading txt file #### > head(raw_data) subject...

r,fread

I am interested to skip some lines of my data frame before the header names . How can i do it by skiping all the lines before ID_REF or if ID_REF is not present, check for the pattern ILMN_ and deleting all the lines keeping immediate first if not containing...

python,datetime,pandas,format,dataframes

I have a large database and I am looking to read only the last week for my python code. My first problem is that the column with the received date and time is not in the format for datetime in pandas. My input (Column 15) looks like this: recvd_dttm 1/1/2015...

r,ggplot2

I'm working with some data that I want to display as a nxn grid of plots. Edit: To be more clear, there's 21 categories in my data. I want to facet by category, and have those 21 plots in a 5 x 5 square grid (where the orphan is by...

r,plot,ggplot2,cdf

Currently I am doing some cumulative distribution plot using R and I tried to set x-axis with decreasing power values (such as 10000,1000,100,10,1) in equal sizes but I failed: n<-ceiling(max(test)) qplot(1:n, ecdf(test)(1:n), geom="point",xlab="check-ins", ylab="Pr(X>=x)")+ geom_step() +scale_x_reverse(breaks=c(10000,1000,100,10,1)) +scale_shape_manual(values=c(15,19)) It seems that the output has large interval for 10000, then all the...

r,statistics,histogram

How do I get a histogram-like summary of interval data in R? My MWE data has four intervals. interval range Int1 2-7 Int2 10-14 Int3 12-18 Int4 25-28 I want a histogram-like function which counts how the intervals Int1-Int4 span a range split across fixed-size bins. The function output should...

r

I have a string which has a complex format, how can I use complex() to treat it as a complex number? For example: myStr="0.76+0.41j" now I want to do sth like: myStr_complex=complex(myStr) # my question is how should I do this part? Eventually Im(myStr_complex) should print 0.41 ...

r,optimization,circular,maximization

Background: I am interested in localizing a sound source from a suite of audio recorders. Each audio array consists of 6 directional microphones spaced evenly every 60 degrees (0, 60, 120, 180, 240, 300 degrees). I am interested in finding the neighboring pair of microphones with the maximum set of...

r,time-series,forecasting

I've been doing a variety of models in R with time series data (in XTS format) and I keep running into the same issue where there's no date / time component to the fitted values / forecasts and thus I can't graph them on the same graph as the original...

r

If I do the following to a string of letters: x <- 'broke' y <- nchar(x) z <- sequence(y) How do I store every value of the z that isn't the first, last, or middle values of the sequence. In this example if z is 1 2 3 4 5...

r,dictionary,spatial

I am working on a large data set with spatial data (lat/long). My data set contains some positions that I don´t want in my analysis (it makes the files to heavy to process in ArcMap- many Go of data). This is why I want to subset the relevant data for...

java,r,rjava

How to call java method which returns list from R Language.

r

I want to model that a factory takes an input of, say, x tonnes of raw material, which is then processed. In the first step waste materials are removed, and a product P1 is created. For the "rest" of the material, it is processed once again and another product P2...

r,posix,posixct

This question already has an answer here: Getting consist units from diff command in R 4 answers I successfully subtracted two POSIXct cols of df1 (below). However, since the time differences are >= 1 hour in all rows, R gives the results in hours. I know that this make...

r,ggplot2

Is there an equivalent in ggplot2 to plot this dataset? I use matplot, and read that qplot could be used, but it really does not work. ggplot/matplot data<-rbind(c(6,16,25), c(1,4,7), c(NA, 1,2), c(NA, NA, 1)) as.data.frame(data) matplot(data, log="y",type='b', pch=1) ...

python,python-2.7,pandas,dataframes

I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

r,time-series

I am trying to fit a subset model with only lag 4. In the manual it's written "you must use p=c(0,0,0,4) since p=4 will fit a full AR(4)". I did this. #fit a subset model with just lag 4 Fit=FitAR(p=c(0,0,0,4), lag.max = "default", ARModel = "ARz") However, I get the...

r,vector,percentage

This is my vector head(sep) I must find percent of all SEP 11 in each row. For instance, in first row, percent of SEP 11 is 100 * ((63 + 124)/ (63 + 124 + 0 + 0)) And would like this stored in newly created 8th column Thanks dput...

r,date,csv

This question already has an answer here: as.Date with dates in format m/d/y in R 2 answers My problem is that the as.Date function does not convert the values in a "date" column of a data frame into Date objects. I have a data.frame nmmaps. Here is a short...

r,string-split,stemming,text-analysis

I had a text data frame having sentences, and as I wanted the list of separate words in another dataframe I used the "qdap package" function "all_words" Words = all_words(df$problem_note_text, begins.with=NULL , alphabetical = FALSE, apostrophe.remove = TRUE, char.keep = char2space, char2space = "~~") Now have a dataframe which has...

r,loops,for-loop,shiny

In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

r,count,duplicates

I've got a column A, which has several values, some of them repeating. So, example: A = c(5, 9, 6, 5, 5). I need to go through A and count the frequencies of each of the values in A. So, for this example, for the set of 5s in A,...

r,large-data

I have a large data set, one of the files is 5GB. Can someone suggest me how to quickly read it into R (RStudio)? Thanks

r,shiny,sleep

I have a WebApp that have some renderUI({})... and some of them depend on the input of another. This makes that, briefly, a red error in the webpage appear when I select some options. Because the if() clause of some renderUI({}) depend on the input of a selectizer. The error...

r,excel

I'm trying to convert a column showing the time of road traffic accidents from military time to standard time. The data looks like this: Col1 Time..24hr. 1 1404 2 322 3 1945 4 1005 5 945 I'd then like to convert to 12hr so for '322' I'd like to make...

r

We have seven exposures and 24 groups. We would like to randomly assign five of the seven exposures to groups while also ensuring that we end up with a consistent count for each exposure, meaning that each exposure ends up being exposed about the same number of times. I have...

r

I'm trying to chop up a text file into the articles it contains. Usually this is done by identifying a pattern each article begins with. Unfortunately the database I downloaded the articles from doesn't have that. The only pattern I can find is that after each article there are 3...

r,if-statement,recursion,vector,integer

Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

r,loops,data.frame,append

How do I put what I printed in a dataframe with a for loop and if else statements? Basically, this code: list<-c("10","20","5") for (j in 1:3){ if (list[j] < 8) print("Greater") else print("Less") }) #[1] "Less" #[1] "Less" #[1] "Greater" Or should it be something more like this? f3 <-...

python,pandas,dataframes,difference

I couldn't find a way to have a dataframe that has the difference of 2 dataframes based on a column. So basically: dfA = ID, val 1, test 2, other test dfB = ID, val 2, other test I want to have a dfC that holds the difference dfA -...

r,data.table

I have the following situation: 1) a list of data tables 2) For testing purposes I deliberately want to (deeply) copy the whole list including the data tables 3) I want to take some element from the copied list and add a new column. Here is the code: library(data.table) x...

r,conditional,subset,find-occurrences

I have quite a simple dataset: ID Value Time 1 censored 1 1 censored 2 1 uncensored 3 1 uncensored 4 1 censored 5 1 censored 6 2 censored 1 2 uncensored 2 2 uncensored 3 2 uncensored 4 2 censored 5 I want to keep the first uncensored occurrence,...

r,graph,highlight

library(season) plot(CVD$yrmon, CVD$cvd, type = 'o',pch = 19,ylab = 'Number of CVD deaths per month',xlab = 'Time') if i wanted to highlight a region of the graph based on x values say from 1994-1998 how do i do this? Any thought would be appreciated Thanks....

r,correlation

I would like to correlate two variables and have the output reported separately for levels of a third variable. My data are similar to this example: var1 <- c(7, 8, 9, 10, 11, 12) var2 <- c(18, 17, 16, 15, 14, 13) categories <- c(1, 2, 3, 1, 2, 3)...

r,google-maps,ggmap

Few days ago I was familiarizing myself with displaying maps, plotting points on the map from http://rpubs.com/nickbearman/r-google-map-making Today, I have intermittent success in displaying maps. library(ggmap) map <- qmap('Anaheim', zoom = 10, maptype = 'roadmap') Outputs Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=Anaheim&zoom=10&size=640x640&scale=2&maptype=roadmap&language=en-EN&sensor=false And when I go to the URL...

python,datetime,pandas,dataframes

I have a large database and I am looking to read only the last week for my python code. However, somebody made a typo in the database so there is a date in the future that is throwing everything off. Input: recvd_dttm 6/5/2015 18:28:50 PM 6/5/2015 14:25:43 PM 9/10/2015 21:45:12...

r,string

I've got a vector with a long list of dataset names. E.g myvector<-c('ds1','ds2,'ds3') I'd like to use the names ds1..ds3 to write a file, taking the file name from the vector. Like this: write.csv(dataset[i],file=paste(myvector[i],'.csv',sep='') with dataset being d1...ds3, but without quotes. How can I remove the quotes and refer to...

r

I am using R for a project and I have a data frame in in the following format: A B C 1 1 0 0 2 0 1 1 I want to return a data frame that gives the Column Name when the value is 1. i.e. Impair1 Impair2 1...

r,oop

I have a number of matrices of the same size: m1.m <- matrix(c(1,2,3,4), nrow=2, ncol=2) m2.m <- matrix(c(5,6,7,8), nrow=2, ncol=2) ... I want to set uniform column and row names to all of them. Currently I am doing it like this: new_col_names <- c("Col1","Col2") new_row_names <- c("Row1","Row2") change_names <- function(m,...

r,dataframes,vectorization

I've got a dataframe that includes columns like the one on the right here: lengthArray speed_max 1 4 24, 18, 24, 18 2 10 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 3 4 -999, -999, -999, -999 4 2 -999, -999 5 2 18, 18 6 1...

r

I have two tables, one with property listings and another one with contacts made for a property (i.e. is someone is interested in the property they will "contact" the owner). Sample "listings" table below: listings <- data.frame(id = c("6174", "2175", "9176", "4176", "9177"), city = c("A", "B", "B", "B" ,"A"),...

r,sapply

This code is suppose to take in a word, and compute values for letters of the word, based on the position of the letter in the word. So for a word like "broke" it's suppose to compute the values for the letter "r" and "k" strg <- 'broke' #this part...

r,rbind

The initial data frame mergedDf is PROD_CODE 1 PRD0900033,PRD0900135,PRD0900220,PRD0900709 2 PRD0900097,PRD0900550 3 PRD0900121 4 PRD0900353 5 PRD0900547,PRD0900614 After calling mergedDf<-data.frame(do.call('rbind', strsplit(as.character(mergedDf$PROD_CODE),',',fixed=TRUE))) Output becomes X1 X2 X3 X4 1 PRD0900033 PRD0900135 PRD0900220 PRD0900709 2 PRD0900097 PRD0900550 PRD0900097 PRD0900550 3 PRD0900121 PRD0900121 PRD0900121 PRD0900121 4 PRD0900353 PRD0900353 PRD0900353 PRD0900353 5 PRD0900547 PRD0900614...

r

user_id date datetime page 217568 6/12/2015 49:23.9 Vodafone | How to get in touch with Vodafone 135437 6/10/2015 43:35.7 My VodafoneÂ â€“ Manage your Vodafone Pay Monthly Account Online â€“ Vodafone 196094 6/13/2015 33:39.4 Check the status of Vodafoneâ€™s mobile network in real-time 74197 6/6/2015 52:46.1 undefined 153501 6/5/2015 02:55.5...

r,google-maps,ggmap

I have a dataset that looks like this: LOCALITY numbers 1 Airoli 72 2 Andheri East 286 3 Andheri west 208 4 Arya Nagar 5 5 Asalfa 7 6 Bandra East 36 7 Bandra West 72 I want to plot bubbles (bigger the number bigger would be the bubble) inside...

r,shiny

I am playing around with the shiny packages for some hours now, and wanted to make a select input widget that enables me to download a certain data set from the server. So i figured out a way to get me this data frame containing all my IDs for downloading:...

r,paste,assign,names

I am using a for loop to read in multiple csv files and naming the datasets import1, import2, etc. For example: assign(paste("import",i,sep=""), read.csv(files[i], header=FALSE)) However, I now want to rename the variables in each dataset. I have tried the following: names(as.name(paste("import",i,sep=""))) <- c("xxxx", "yyyy") But get the error "target of...