Menu
  • HOME
  • TAGS

Combining lists in python with unique elements but changing the third

python,merge,unique,mean

Use dictionary to collect items based on their first two elements: expressions = {} for left, op, right in list1 + list2: expressions.setdefault((left, op), []).append(right) then build a new list with the mean of the collected right-hand-side operands: [[left, op] + [sum(rights) // len(rights)] for (left, op), rights in expressions.items()]...

CSV conversion in R for standard calculations

r,csv,import,mean

In addition to @akrun's advice, another option is to convert the columns to numeric yourself (rather than having read.csv do it): dati <- data.frame( lapply(dataGSR[-c(1:3),-9],as.numeric)) ## R> colMeans(dati) Shimmer Shimmer.1 Shimmer.2 Shimmer.3 Shimmer.4 Shimmer.5 Shimmer.6 Shimmer.7 33004.2924 18647.4609 707.4335 718.3989 2521.3626 3672.1383 2497.9013 3659.9287 Where dataGSR was read in with...

How to compare each matrix to mean and return value in Matlab

arrays,matlab,matrix,mean

It seems you want to know whether each entry is greater than its column-mean. This is done efficiently with bsxfun: result = bsxfun(@gt, a, mean(a,1)); Example: a = 3 1 3 2 5 2 3 1 1 3 5 2 The column-means, given by mean(a,1), are ans = 3.000000000000000 2.000000000000000...

Python pandas - averaging 10 min measurements to 15min mean and 60min mean depending on the length of the data gap

python,pandas,mean,na

# Setup problem import pandas as pd import numpy as np num_samples = 100 s = pd.Series(np.random.randint(0, 500, num_samples), index=pd.date_range('03/06/2015', periods=num_samples, freq='10min')) mask = np.random.rand(num_samples) < .7 s[mask] = np.nan # Loop through index # Note the perc_nan variable can be changed depending on what percentage of the interval must...

Memory leak caused by gulp & nodemon

node.js,gulp,mean,nodemon,gulp-livereload

Looks like the issue is this .on('start', ['watch']) .on('change', ['watch']) .on('restart', function () { console.log('restarted!'); }); Everytime a file changes, you're triggering watch which attaches additional listeners. After a few restarts, you will exceed the max number of listeners. This is a standard nodemon setup, and is all you need...

NodeJS/MEAN.io temp files

node.js,file,filesystems,mean

bodyParser() no longer deals with grabbing uploaded files (multipart was removed from it sometime mid-2013), so by itself there's no issue with temp files. If you are using one of the multipart middleware packages (busboy, formidable, et al.), you'll have to take care of temp files explicitly. This usually isn't...

My service is returning the function's text and not an object

angularjs,mongodb,mean

You are overriding your object with function. Just give them different names and it should work just fine. this.newMarker = { ... }; this.getNewMarker = function () { return this.newMarker }; EDIT: You should also always create new instance from marker. Otherwise you just edit the same object all the...

R mean values of a sum of Matrices without divide for points equal zero

r,matrix,sum,mean,zero

You can do (A+B)/((A!=0) + (B!=0)) to get [,1] [,2] [,3] [1,] 1 1 2 [2,] 2 3 2 [3,] 3 2 2 Here != tests for equality with zero returning TRUE or FALSE. When we add those up, the TRUEs are treated like 1 and the FALSEs become 0....

Mean by levels of factor in R, append as new column [duplicate]

r,apply,mean

You could use ave from base R test$meanbyname <- with(test, ave(value, name)) Or using mutate from dplyr or := in data.table, can get the results i.e. library(dplyr) group_by(test, name) %>% mutate(meanbyname=mean(value)) Or library(data.table) setDT(test)[, meanbyname:= mean(value), by=name] ...

mean(rnorm(100,mean=0,sd=1)) is not 0; and sd(rnorm(100,mean=0,sd=1)) is not 1. Why?

r,mean,standard-deviation

rnorm(100) gives you a random sample of 100 values from distribution mean = 0 and sd = 1. Because it is random, the actual value of mean(rnorm(100)) depends on which particular values you get back. There is no guarantee that the mean will be 0, but statistically it should converge...

awk geometric average on the same row value

arrays,bash,awk,mean

Having this file: $ cat infile "ID1","Cpd_number","ID2","ID3","activity" "95","123","4","5","10" "95","123","4","5","100" "95","123","4","5","1" "95","123","4","6","10" "95","123","4","6","100" "95","456","4","6","10" "95","456","4","6","100" This piece: awk -F\" 'BEGIN{print} # Print headers last != $4""$8 && last{ # ONLY When last key "Cpd_number + ID3" print line,exp(C/D) # differs from actual , print line + average C=D=0} # reset acumulators...

calculate mean or variance for subset of pandas DF column

python,pandas,mean

It's not totally clear what exactly you want to do, but it looks like what you mean is taking the per-row average of columns A-D. In which case, you're just giving the wrong axis argument. DF['means']=DF[['A','B','C','D']].mean(axis=1) should work fine....

Angular statistics doesn't make sense

statistics,mean,angle,direction

The values don't look right Angles that differ by 360 are equivalent. So, -28.8551147 == 331.145, which is the arithmetic mean of the two values you provided. If you would like to ensure that your values are always in [0,360), you should add 360 if the values are less...

npm install mongoose on windows 7 failing

node.js,mongoose,npm,mean,bson

Finally I am able to install mongoose on windows 7 below are my findings/solutions I found out problem was with mongodb which is itself a node module and a dependency for mongoose.The mongodb module was not build properly becasue I had not install Visual Studio c++ 2010. So I install...

Three-way graph (variable, mean, sd) with ggplot2

r,ggplot2,mean,facet,standard-deviation

Here's my approach to the solution outlined by @DavidArenburg (though I simplified the data a little, using simple cumulative statistics and a plain index): library(tidyr) library(dplyr) library(TTR) v <- rnorm(1000) df <- data.frame(index = 1:1000, variable = v, mean = runMean(v, n=1, cumulative=TRUE), sd = runSD(v, n=1, cumulative=TRUE)) dd <-...

How to calculate rolling Geometric Mean since inception in R

r,xts,mean

Transferred from comments. RET is an xts object and rollapply.xts in the xts package does not support vector widths. Try this to cause it to use rollapply.zoo in the zoo package: rollapplyr(as.zoo(RET), 1:nrow(RET), mean.geometric) ...

anchor tag href not linking with div id

javascript,jquery,html,css,mean

I believe the problem is that since you are doing this inside an Angular controller, Angular thinks that the #yes anchor is referring to a specific route, not just a plain old anchor within the page. If I remember correctly, specifying target="_self" on the link will tell Angular to just...

Mean per group in a column, result per row

r,data.frame,mean

I would suggest the "data.table" package for this: sdcols <- names(DF)[-1] ## A vector of the new columns we want to add as.data.table(DF)[, paste(sdcols, "mean", sep = "_") := lapply(.SD, mean), by = ID][] ## you can also be more specific and specify sdcols # ID C1 C2 C1_mean C2_mean...

Mean of column based on multiple conditions in R

r,rows,mean

You may want to play around with aggregate For instance: aggregate(DF$mw3wuus, FUN=mean, by=list(y1=DF$y1, y0=DF$y0, y3=DF$y3, y4=DF$y4)) Will give you: y1 y0 y3 y4 x 1 AG 2 1994 AA 45.5 2 AI 1 1997 AA 22.0 3 AI 1 1994 EB 78.0 4 AI 1 1999 EB 21.0 5 AG...

How to catch the error when inserting a MongoDB document which violates an unique index?

javascript,mongodb,express,mongoose,mean

You will need to test the error returned from the save method to see if it was thrown for a duplicative username. app.post('/authenticate', function(req, res) { var user = new User({ username: req.body.username }); user.save(function(err) { if (err) { if (err.name === 'MongoError' && err.code === 11000) { // Duplicate...

How exactely are outliers removed in R boxplot and how can the same outliers be removed for further calculation (e.g. mean)?

r,mean,outliers

To remove the outliers, you must set the option outline to FALSE. Let's assume that your data are the following: data <- data.frame(a = c(seq(0,1,0.1),3)) Then, you use the boxplot function: res <- boxplot(data, outline=FALSE) In the res object, you have several pieces of information about your data. Among these,...

Summarise with dplyr and export table with means and sd (+/-)

r,export,dplyr,mean

Do you mean like this? library(knitr) dfc[c(-1,-2)] <- signif(dfc[c(-1,-2)], digits = 4) dfc_str <- transmute(dfc, TRA, Comp1 = paste(meanComp1, " +/-", sdComp1), Comp2 = paste(meanComp2, " +/-", sdComp2), Comp3 = paste(meanComp3, " +/-", sdComp3)) kable(dfc_str) ...

Take mean of two or more DataFrames in Python

python,pandas,dataframes,mean

you can add the two DataFrames together to get a new one: (a+b)/2 Output: 0 1 0 1 1 1 6 6 [2 rows × 2 columns] Or if you wanted to do some more complicate processing on the result: c = a+b c.std() output: 0 7.071068 1 7.071068 ...

rollmean length of timeseries

r,time-series,mean,moving-average

I am not completely clear on how you want to do the filling but here are some ways: 1) Add the argument fill = NA to rollmean to add NA's to the ends. 2) If you want partial means at the ends then use this where x is your data,...

Calculate mean of each n-rows in a dataframe in r when the first row is varying

r,data.frame,mean

You could try Map. lst <- Map(function(x,y) {x1 <- x[y:length(x)] tapply(x1,as.numeric(gl(length(x1), 5, length(x1))), FUN=mean)}, df, df1) lst # $X1 # 1 2 3 4 5 6 #-0.16500158 0.11339623 -0.86961872 -0.54985564 0.19958461 0.35234983 # 7 8 9 10 11 12 #0.32792769 0.65989801 -0.30409184 -0.53264725 -0.45792792 -0.59139844 # 13 14 15 16...

Mean stack Schema

javascript,node.js,mongodb,mongoose,mean

By adding an attribute in the ChartSchema or an Array of Chart in the UserSchema. Add and _id field on both Schema. ChartSchema = new Schema({ // ... _creator: { type: Number, ref: 'User' }, }); Or UserSchema = new Schema({ // ... chartsCreated: [{ type: Number, ref: 'Chart' }]...

Average a subset of a matrix in a loop in matlab

matlab,image-processing,matrix,mean,subsetting

Method 1 Using mat2cell and cellfun AC = mat2cell(A, repmat(2,size(A,1)/2,1), repmat(2,size(A,2)/2,1)); out = cellfun(@(x) mean(x(:)), AC); Method 2 using im2col out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2); Method 3 Using simple for loop out(size(A,1)/2,size(A,2)/2) = 0; k = 1; for i = 1:2:size(A,1) l = 1; for j = 1:2:size(A,2) out(k,l) = mean(mean(A(i:i+1,j:j+1)));...

How do I get the number of input values from a text file in Java SE?

java,average,mean

Just count the number of doubles as you go along, and then work out the mean once you're done scanning the file. int count = 0; while (inputStream.hasNextDouble ()) { count ++; x = inputStream.nextDouble (); y += x; System.out.println (x); } // divide y by count for the mean...

mean.js uses require without var

express,mean,meanjs

The code in the express.js file executes the contents of your model files. The anatomy of a MEAN.js model file is the following; Load the mongoose and schema packages, along with all your included models (if any). Declare the schema for the given model Register the given schema under the...

Averaging values between paired columns across a large data frame

r,apply,mean,sapply,tapply

Try mapply(function(x,y) tapply(x,y, FUN=mean) , Example[seq(1, ncol(Example), 2)], Example[seq(2, ncol(Example), 2)]) Or instead of seq(1, ncol(Example), 2) just use c(TRUE, FALSE) and c(FALSE, TRUE) for the second case...

trying to install bcrypt into node project + node set up issues

node.js,npm,mean

OP managed to fix this for themselves with: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer/ but graciously accepted my answer anyway. Original answer below: There are two distinct problems here. One is that your node is slightly out of date and your npm is substantially out of date. You're using OSX, so there...

Mean.js angularjs querying the mongodb database

angularjs,mongodb,mean

I guess the answer was a bit more complicated. This is working, although there may be a better way to do it. I had to create a new function in one of the app user controllers: exports.userByEmail = function(req, res, next, email) { console.log('userByEmail ' + email); User.findOne({ email: email...

specific gnuplot by data grouping

data,gnuplot,std,mean

Usually, gnuplot isn't made for such data processing tasks. That's best done with an external script, which does the processing and writes to stdout, which can then be feed directly to gnuplot like plot '< python myscript.py simulationR.txt' In your example, you can only have fixed data after the plot...

Compute row-means in a df

r,data.frame,rows,apply,mean

You could use rowMeans transform(mix, Mean=rowMeans(mix[,2:3]), check.names=FALSE) # agrp 1998-1999 2000-2001 tot Mean #1 1 140903 72208 213111 106555.5 #2 2 88322 33704 122026 61013.0 #3 3 18175 3804 21979 10989.5 #4 4 6125 797 6922 3461.0 ...

Mongoose validation exception not caught

node.js,mongodb,mongoose,mean

why don't you do it this way instead: User.save(function (err, user) { if (err) { return res.status(400).json({ _status: 400, _content: { message: err.toString() } }); } res.status(200).json({ _status: 200, _content: { message: "OK", data: user } }); }); Your code won't work because try catch won't be able to catch...

Java program calculates averages. How do I display highest average?

java,loops,average,mean

Just keep track of the highest average in another variable. Then in your score == -1 condition check to see if the current average is higher than the highest average, and if so make current the new highest. Then after your for loop you could print out the highest average.

Calculating mean of certain list values in Python

python,list,mean

Actually its not the mean of the first line, its the mean from the last. After the first list comprehension, row assumes the value of the last row, and when you use row[2] to create numbers list, you create a static list using the values from the last row. You...

Link two dictionaries lists and calculate average values

python,list,join,mean

Given those data structures that you use, this is not trivial, but it will become much easier if you use a single dictionary mapping items to their values, instead. First, let's try to re-structure your data in that way: values = {entry['ptid']: entry['Value'] for entry in dctData} items = {}...

Can't set headers after they are sent on express

javascript,node.js,express,mean

You're sending a response twice via res.end(). Get rid of the second one and you should be fine. Also, calling res.end() after res.render() is redundant since res.render() automatically ends the response with the rendered result by default.

Rolling past and future averages from current value

r,time-series,average,mean,moving-average

For returning the last value try: values$last = c(NA,values[-nrow(values),1]) or the lag function could be used as well I believe....

Weather api for providing weather forecast based upon location

mean,weather-api

You can check these ones : https://developer.forecast.io/docs/v2 http://www.openweathermap.com/API http://api.accuweather.com/developers/ Besides, you can use Google with the following keywords : "weather forecast api"...

How to unscale the coefficients from an lmer()-model fitted with a scaled response

r,mean,lme4,lmer

Updated: generalized to allow for scaling of the response as well as the predictors. Here's a fairly crude implementation. If our original (unscaled) regression is Y = b0 + b1*x1 + b2*x2 ... Then our scaled regression is (Y0-mu0)/s0 = b0' + (b1'*(1/s1*(x1-mu1))) + b2'*(1/s2*(x2-mu2))+ ... This is equivalent to...

Double For Loop & If Else statement to calculate averages and store them in a matrix

r,if-statement,for-loop,matrix,mean

I reckon this is what you need: A<-c(1,2,3,4,5) B<-c(2,3,4,5,6) Q1<-data.frame(cbind(A,B)) res <- outer(A, B, "+")/2 diag(res) <- NA res The outer() function does all the magic. Result: [,1] [,2] [,3] [,4] [,5] [1,] NA 2.0 2.5 3.0 3.5 [2,] 2.0 NA 3.0 3.5 4.0 [3,] 2.5 3.0 NA 4.0 4.5...

Using slugs in URL in CRUD in MEANJS

node.js,express,mean,mean-stack,meanjs

I cloned the 0.4.0 branch and here's what I did to make the routing by slug working as it should in all scenarios. 1- Add the slug to the article schema and ensure its unique article.server.model.js slug: { type: String, default: '', trim: true, unique: true, required: 'Slug cannot be...

MATLAB: mean(X(Y == y, :));

matlab,mean

Unpacked, this single line might look like: row_indices = find(Y==y); new_X = X(row_indices,:); params.means(k,:) = mean(new_X); So, as you can see, the Y==y is simply being used to find a subset of X over which the mean is taken. Given that you said that this was for computing multivariate Gaussian...

functions na.rv(T), na.omit, is.finite, etc. don't work for the mean of a column

r,mean,na,inf

You need to do the following: #since you don't care about the Infs convert them to NAs #so that they get removed at the mean function #since we have set na.rm=TRUE df$amihud[df$amihud==Inf] <- NA library(dplyr) #you need to use summarise to calculate the means as below: res <- df %>%...

Calculate dataframe mean by skipping certain values in Python / Pandas

python,pandas,nan,mean

The skipna arg is a boolean specifying whether or not to exclude NA/null values, not which values to ignore: skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA Assuming I understand what you're trying to do, you could replace -9999...

Python— Mean and Standard Deviation over groups of columns

python,numpy,std,mean

Use as a numpy array as such: include numpy as np np.std(array) Example of grabbing parts of array: a = [1 2 3] a[0:1] = [1] a[0:2] = [1 2] Also for 2D (or higher) array, a = [[1,2,3,4,5,6],[1,2,3,4,5,6]] b = np.array(a) print b[:,:3] [[1 2 3 4] [1 2...

MEAN return from http get

javascript,angularjs,express,mean

Angular works with async proccessing and callback digestions, which mean your http call retrun a promise object who get resolved when data arrived. You should use angular's $http service. As mentioned in the documentation: The $http service is a function which takes a single argument — a configuration object —...

exact value of the mean of a boxplot

r,ggplot2,mean,boxplot

I would approach such a task using aggregate or plyr. With aggregate you get the group means (of Fracht I assume) with the following call: groupMeans <- aggregate(Fracht ~ Bewirtschaftungsform, daten, mean) Rounding is suggested for printing: groupMeans$Fracht <- round(groupMeans$Fracht, 2) Within the ggplot object you can then just add:...

Create a list of midpoints of a sorted list

r,vector,mean,sorted

As indicated by @Khashaa in the comments, you can use rowMeans after using embed or you can use rollmean from the "zoo" package. Example: a <- 1:4 rowMeans(embed(a, 2)) # [1] 1.5 2.5 3.5 library(zoo) rollmean(a, 2) # [1] 1.5 2.5 3.5 If these are too obscure, a similar concept...

Weighted mean in numpy/python

python,numpy,statistics,mean,weighted

You actually have 2 different questions. How to make data discrete, and How to make a weighted average. It's usually better to ask 1 question at a time, but anyway. Given your specification: xmin = -100 xmax = 100 binsize = 20 First, let's import numpy and make some data:...

mean.js menu isPublic not working

angularjs,node.js,mongodb,express,mean

If you look in menus.client.services.js in the core module of mean.js the last line looks like this: this.addMenu('topbar');. If you change it to this.addMenu('topbar', true);. You will see all your menu items showing on the topbar when you aren't logged in. Then you can add your menu item like in...

R - how to calculate “global” monthly means of a zoo object

r,time-series,mean,zoo

1 You can aggregate with a data.table library(data.table) # This turns all Jans to 1 and Decs to 12 for example mth <- month(as.Date(df$date)) dt2 <- as.data.table(df) # turn df into data table dt dt2[, mth := mth] # pop month into your data frame setkey(dt2, "mth") # data tables...

Calculate average from a series with fixed interval

matlab,mean

The number of elements in your original series will always be a multiple of 12, so you can use reshape() to yield an 12 x n matrix. From there using mean() is straightforward to get the vector that you want. nSessions = 20; % Choose an integer to test number...

Java how to compute average scores using loops

java,loops,average,mean

You haven't explicitly asked a question so I'll try and comply to the "set me in the right direction" part. I'd suggest re-formatting the loop structure to a cleaner one, like this: double total; for(int student = 1; student <= 4; student++) { System.out.printf("Student %d\n", student); double sum = 0,...

Calculating mean by selecting from two columns in a data frame [duplicate]

r,data.frame,mean

assuming you data is named df, you can try aggregate aggregate(Value~Month+Station, data=df, FUN = mean) Month Station Value 1 1 ANT 83.5 2 2 ANT 118.5 3 3 ANT 108.5 4 1 ARO 52.0 5 2 ARO 66.5 6 3 ARO 78.5 ...

Add users roles in Meanjs

roles,mean,mean-stack,meanjs

The meanjs generator comes with some basic user roles built in. The roles is an array on the user model. roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, To add a user with the role admin just attach it to the user object before saving....

Loop function and add columns to dataframe in R

r,function,loops,mean,sapply

Try this: Just to clear the confusion. dat1=as.data.frame(matrix(rnorm(25),ncol=5)) dat5=as.data.frame(matrix(rnorm(25),ncol=5)) dat7=as.data.frame(matrix(rnorm(25),ncol=5)) my_fun <- function(dataframe){ rowMeans( dataframe[ , c("V1","V2")],na.rm=TRUE) } dfList<-list(dat1,dat5,dat7) Vars <- grep("dat", ls(), value=TRUE) Vars #[1] "dat1" "dat5" "dat7" res <- lapply(dfList, function(x) transform(x,V6=my_fun(x))) for(i in 1:length(Vars)){ assign(Vars[i], res[[i]],envir=.GlobalEnv) } A Second function: my_funSD <-...

Why is boot returning all NA values

r,mean,difference,resampling

It's generally unwise to use subset within functions, but even more unwise to index with a vector that is of a different length than the number of rows of the data-object. The boot function passes a series of index vectors of row-names that have been sampled with replacement from the...

Why do mean() and mean(aggregate()) return different results?

r,aggregate,mean,na

I think this is because in the mean(dat$x, na.rm=T) version, each NA that is removed, reduces the number of observations by 1, whereas if you aggregate first, in your example you have an NA in row 10 (ID 11) which is removed but since the other rows with ID 11...

Calculating mean for every second value in a dataframe

r,data.frame,aggregate,mean

Here's a possible data.table solution library(data.table) setDT(df)[, .(Y = Y[1L], Z = mean(Z)), by = .(X, indx = cumsum(substr(Y, 11, 12) == '00'))] # X indx Y Z # 1: FRI 1 200101010000 -6.510 # 2: FRI 2 200101010100 -6.040 # 3: FRI 3 200101010200 -5.465 # 4: FRI 4...

compute a Means variable for a specific value in another variable

r,group-by,frame,mean

You could try data.table library(data.table) as.data.table(work1)[, .(dead_sum=sum(dead), surv_sum=sum(surv), age_mean=mean(age)), keyby=.(period, diagnosis)] Or dplyr library(dplyr) work1 %>% group_by(period, diagnosis) %>% summarise(dead_sum=sum(dead), surv_sum=sum(surv), age_mean=mean(age)) # result period diagnosis dead_sum surv_sum age_mean 1: 1 1 1 3407 57.00000 2: 2 1 0 3783 25.00000 3: 3 1 0 9262 33.33333 4: 4 1...

Unsure how to pass column variable to mean() in r

r,variables,mean

(df.final <- data.frame(ford = sample(0:100, 5), toyota = sample(0:50, 5))) # ford toyota # 1 42 5 # 2 30 46 # 3 45 29 # 4 69 48 # 5 18 14 col.name # [1] "df.final$ford" typeof(col.name) # [1] "character" Currently, col.name is a character vector, so taking its...

How do I print an ArrayList reading top-to-bottom in Java?

java,list,arraylist,mean

It is not natively supported, but you can use a simple loop: for (Object o : exes) System.out.println(o); or use regex kung fu for a one-liner: System.out.println(exes.toString().replaceAll("^.|.$", "").replace(", ", "\n")); which modifies the output of the toString() to the format you want. or in java 8: exes.forEach(System.out::println); ...

calculate mean for Long Format - n_distinct issue and group_by issue

r,dplyr,mean,summary

Hm, I guess reusing group_by with add=TRUE is one way: dta %>% group_by(isex) %>% mutate( ng = n_distinct(idno) ) %>% group_by(value,add=TRUE) %>% summarise( smn = 10*n(), mean = 10*n()/ng[1] ) # isex value smn mean # 1 FEMALE a Sleep 150 75 # 2 FEMALE j Child care 10 5...

r search along a vector and calculate the mean

r,vector,mean

We could use rleid to create another grouping variable, get the mean of 'y', and assign the 'indx' to NULL library(data.table) # v 1.9.5+ DT[, .(my = mean(y)), by = .(indx = rleid(x), x)][, indx := NULL] # x my #1: 19 54 #2: 21 38 #3: 19 47 #4:...

Calculate mean of sub arrays within a larger 3D array in Python

python,arrays,numpy,mean

I assume that you want to calculate the mean value of entries (0,0), (0,1), (1,0), (1,1), then of (2,2), (2,3), (3,2), (3,3), and so on. You select every second column and row, four times, starting with indices (0,0), (0,1), (1,0) and (1,1), respectively. Then, you divide by 4 and round...

Function can't see change in array

javascript,angularjs,function,angularjs-scope,mean

Your first function contains this line: $scope.selected.project = [$model]; So, if you set $model to 1 (which you do in the line above), it will, of course, return [1]. In your second function, I can't see $scope.selected.project on the left-hand side of any assignment, so it simply isn't assigned the...

Double For Loop and calculate averages in R

r,for-loop,mean

What I think you're asking is this: given two vectors of numbers, how can I find the mean of the first items in each vector, the mean of the second items in each vector, and so on. If that's the case, then here is a way to do that. First,...

summarize all numeric columns of data frame by group in R

r,data.frame,plyr,mean,summary

I think you're looking for numcolwise? ddply(diamonds,.(cut),numcolwise(mean,na.rm = TRUE)) cut carat depth table price x y z 1 Fair 1.0461366 64.04168 59.05379 4358.758 6.246894 6.182652 3.982770 2 Good 0.8491847 62.36588 58.69464 3928.864 5.838785 5.850744 3.639507 3 Very Good 0.8063814 61.81828 57.95615 3981.760 5.740696 5.770026 3.559801 4 Premium 0.8919549 61.26467 58.74610...

R: aggregate quarterly data to hourly data - different behaviour with same date fields

r,date,aggregate,average,mean

Too long for a comment. The reason your results look different is that aggregate(...) sorts the results by your grouping variable(s). In the first case, strftime(data.15min$posix, format="%m/%d/%y %H") is a character vector with poorly formatted dates (they do not sort properly). So the first row corresponds to the "date" "01/01/96...

Python Pandas : group by in group by and average?

python,pandas,group-by,mean

If you want to first take mean on ['cluster', 'org'] combination and then again take mean on cluster groups In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean() .groupby('cluster')['time'].mean()) Out[59]: cluster 1 15 2 54 3 6 Name: time, dtype: int64 If you wan't mean values by cluster only, then you could In [58]:...

Why does mean give NA?

r,mean

Mean does not work on data.frames. It only works on vectors and matrices. If you try mean(as.matrix(tQs)) it should work - assuming there is no problem with the underlying data....

Finding the mean using a function. vb.net

arrays,vb.net,function,mean

When you do this Dim DblArray(lstbxInput.Items.Count - 1) As Double All of DblArray items are 0, but you never change any of the DblArray items in your code, so dblmean would also be 0. You need to assign each item of DblArray before calculating the mean. I would guess this...

Using Mean Function for a specified part of column of a matrix in R

r,matrix,statistics,mean

I guess you need mean(z[,1][70 <= z[,2] & z[,2] <= 72], na.rm=TRUE) data set.seed(45) z <- matrix(sample(c(NA,70:80), 5*10, replace=TRUE), ncol=5, nrow=10) ...

Calculating Function from Variable 1 after Eliminating Level(s) from Variable 2 Using R

r,subset,mean,subsetting

You were close, try this mean(iris$Sepal.Length[which(iris$Species != 'setosa')]) or mean(iris$Sepal.Length[iris$Species != 'setosa']) or mean(iris[iris$Species!= "setosa", "Sepal.Length"]) ...

PYTHON: Finding the average of values of a nested list

python,list,average,mean

You can use zip within a list comprehension: >>> from __future__ import division >>> [[set(i).pop(),round(sum(j)/len(j),0)] for i,j in [zip(*i) for i in data]] [['apple', 2.0], ['cake', 7.0], ['chocolate', 7.0], ['grapes', 6.0]] The zip function here would separate your values from names in nested lists: >>> [zip(*i) for i in data]...

Double For Loop to calculate averages and store them in matrix

r,for-loop,mean

[Original Solution (see Update 2 for the faster solutions)] f.m <- function(Q1) { z <- matrix(nrow=nrow(Q1),ncol=nrow(Q1)) b <- row(z) < col(z) z[b] <- (Q1$A[col(z)[b]] + Q1$B[row(z)[b]])/2 z } [Sample output] f.m(Q1) # [,1] [,2] [,3] [,4] [,5] # [1,] NA 2 2.5 3.0 3.5 # [2,] NA NA 3.0 3.5...

mean day with hourly data from a week matlab

matlab,data,average,mean,days

I don't understand why not use reshape? reshaped = reshape( allData, [24 7 52] ); avg = mean( reshaped, 2 ); %// average over the seven days You might want to squeeze the result at the end......

MEAN entities association

angularjs,mongodb,express,mongoose,mean

The solution I found (I am not sure if it is the correct solution or a workaround) is to populate the .idea field of a poll with its corresponding ._id: var poll = new Polls ({ idea: this.idea._id, vote1: 5, vote2: 3, vote3: 3, vote4: 1, vote5: 2 }); At...

AngularJS Mean.js Atom Beautifier Javascript Issue

javascript,angularjs,mean,atom

This actually bit me once before and I STILL was stumped by it when it bit me again just now. Two curly brackets ({{...}}) tells AngularJS to evaluate the contents as an expression. Beautifier breaks this by helpfully breaking up the doubled curly brackets into separate lines. Because that's what...

How to plot deviation from mean

r,ggplot2,mean

Perhaps you want: rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) } set.seed(101) r <- rnorm2(100,4,1) x <- seq_along(r) ## sets up a vector from 1 to length(r) par(las=1,bty="l") ## cosmetic preferences plot(x, r, col = "green", pch=16) ## draws the points ## if you don't want points at all, use ## plot(x,...

Strange behaviour of mean() in Matlab

matlab,mean

MATLAB is performing the calculation correctly, but the default number format (short-fixed) for the display makes the 3 and 9 appear to be 0 since the other numbers are large. You can change the format using format. When you change it to short-exponential format, you get Octave's output (since it...

Datetime objects with pandas mean function

python,datetime,pandas,mean

You can use datetime.timedelta d={'one' : Series([1, 2, 3], index=['a', 'b', 'c']), 'two' :Series([datetime.datetime(2014, 7, 9) , datetime.datetime(2014, 7, 10) , datetime.datetime(2014, 7, 11) ], index=['a', 'b', 'c'])} df = pd.DataFrame(d) def avg_datetime(series): dt_min = series.min() deltas = [x-dt_min for x in series] return dt_min + functools.reduce(operator.add, deltas) / len(deltas)...

MEAN failed to deploy

google-compute-engine,mean

Try using Bitnami's prebuilt MEAN stack to deploy MEAN on Google Compute Engine.

Substituting the results of a calculation

r,mean,gsub,strsplit

You need a single regex in strsplit for this task (removing letters and splitting): s4[] <- lapply(s4, function(x) { if (is.numeric(x)) x else sapply(strsplit(as.character(x), "-|[[:alpha:]]"), function(y) mean(as.numeric(y))) }) The result: > s4 X1a X1b X1a.1 X1b.1 1 5.27 4.76 5.090 4.750 2 2.47 2.74 2.770 2.800 4 1.14 1.38 1.120...

how to deal with NaN, Na and Inf to calculate mean in R? + after measuring community detection metrics [closed]

r,nan,mean,na

Well, I would distinguish between the cases of NA/NaN/Infinity and the rest. I would certainly not convert them to zero as this would distort the result significantly while at the same time, not having any real mathematical sense. If a value is NA, then it is not, as the name...

How to write an R code which calculates the row-wise mean from an Excel file? [closed]

r,excel,mean

Use e.g. the readxl package: library(readxl) df <- read_excel(filename, sheetnumber) rowMeans(df[, -1]) # [1] 21.66667 45.00000 66.33333 43.00000 ...

Manipulating values in python dictionaries

python,python-3.x,dictionary,mean,median

I don't know how to manipulate the values to find the names of all the students whose grades are above the mean for the class. (the mean being the sum of the values divided by the number of values). You can use a list comprehension to create a sublist...

Grouping data in Python with pandas yields a blank first row

python,pandas,group-by,mean

That's just a display thing, the grouped column now becomes the index and this is just the way that it is displayed, you will notice here that even when you set pd.set_option('display.notebook_repr_html', False) you still get this line, it has no effect on operations on the goruped df: In [30]:...

how to calculate the mean with conditions? [duplicate]

r,condition,mean

Here's a quick data.table solution (assuming coef is a) library(data.table) setDT(df)[, .(MeanASmall = mean(b[-40 <= a & a < 0]), MeanABig = mean(b[0 <= a & a <= 40]))] # MeanASmall MeanABig # 1: 33.96727 89.46 If a range is limited, you could do this quickly with base R too...

Creating a matrix of means based on column time series in R [closed]

r,matrix,mean

It's very simple. First, you should calculate mean for each column, then you should reshape resulting 1x25 vector into 5x5 matrix: matrix(apply(data,2,mean), nrow=5, ncol=5, byrow=TRUE) apply(data,2,mean) calculates mean values for each column of data and matrix constructs a 5x5 matrix from its results....

Matlab: Calculating Correlation of time series

matlab,time-series,covariance,mean

I'm not sure that I understand all of the details of your question, but if you just want to operate on a delayed version of a signal, you can do something like this... %xcorr with a 1-sample shifted version of itself [c,lags]=xcorr(t(1:end-1),t(2:end)); %xcorr with a 2-sample shifted version of itself...

Column means for several columns

r,mean

For your two questions, you can save key strokes by using paste or grepl such as rowMeans(df[grepl("^no2", names(df))]) Or rowMeans(df[paste0("no2_", 1:6)]) Or rowMeans(df[paste0("bc_", 1:5)]) For the last question, use rowSums instead, and divide by the number of columns temp <- df[c("no2_1","no2_2")] rowSums(temp, na.rm = TRUE)/ncol(temp) # 1 2 3 4...