Search Results

Search found 23 results on 1 pages for 'ifelse'.

Page 1/1 | 1 

  • My ifelse statement's result depends on the actions for true/false?

    - by Antal
    Currently I am building a route for a truck to drive inside my netlogo-land. When the truck is next to the shop-patch where it should deliver, the truck needs to change its actions. However my if or ifelse statement does not seem to respond well and the answer depends on the output. With some tests: turtles ifelse ((patch (first dirx) (first diry)) = one-of neighbors4) [write "11"] [write "22"] "11" turtles ifelse ((patch (first dirx) (first diry)) = one-of neighbors4) [write "111"] [write "122"] "122" turtles ifelse (patch (first dirx) (first diry)) = one-of neighbors4 [write "111"] [write "122"] "122" turtles ifelse (patch (first dirx) (first diry)) = one-of neighbors4 [write "11"] [write "12"] "12" turtles ifelse (patch (first dirx) (first diry)) = one-of neighbors4 [write "11"] [write "22"] "11" Please note that during this time I do not move my truck, I use the command center to ask these questions (from turtle truck perspective). I am very confused about this. As the only thing I change is the action (what to write). This should not impact the true/false statement itself. Does anybody have any clue what is going on here and why the ifelse responds strange?

    Read the article

  • NetLogo 4.1 - implementation of a motorway ( Problem creating collision of cars )

    - by user206019
    Hi there, I am trying to create a simulation of motorway and the behaviour of the drivers in NetLogo. I have some questions that I m struggling to solve. Here is my code: globals [ selected-car ;; the currently selected car average-speed ;; average speed of all the cars look-ahead ] turtles-own [ speed ;; the current speed of the car speed-limit ;; the maximum speed of the car (different for all cars) lane ;; the current lane of the car target-lane ;; the desired lane of the car change? ;; true if the car wants to change lanes patience ;; the driver's current patience max-patience ;; the driver's maximum patience ] to setup ca import-drawing "my_road3.png" set-default-shape turtles "car" crt number_of_cars [ setup-cars ] end to setup-cars set color blue set size .9 set lane (random 3) set target-lane (lane + 1) setxy round random-xcor (lane + 1) set heading 90 set speed 0.1 + random 9.9 set speed-limit (((random 11) / 10) + 1) set change? false set max-patience ((random 50) + 10) set patience (max-patience - (random 10)) ;; make sure no two cars are on the same patch loop [ ifelse any? other turtles-here [ fd 1 ] [ stop ] ;if count turtles-here > 1 ; fd 0.1 ;if ; ;ifelse (any? turtles-on neighbors) or (count turtles-here > 1) ;[ ; ifelse (count turtles-here = 1) ; [ if any? turtles-on neighbors ; [ ; if distance min-one-of turtles-on neighbors [distance myself] > 0.9 ; [stop] ; ] ; ] ; [ fd 0.1 ] ;] ;[ stop ] ] end to go drive end to drive ;; first determine average speed of the cars set average-speed ((sum [speed] of turtles) / number_of_cars) ;set-current-plot "Car Speeds" ;set-current-plot-pen "average" ;plot average-speed ;set-current-plot-pen "max" ;plot (max [speed] of turtles) ;set-current-plot-pen "min" ;plot (abs (min [speed] of turtles) ) ;set-current-plot-pen "selected-car" ;plot ([speed] of selected-car) ask turtles [ ifelse (any? turtles-at 1 0) [ set speed ([speed] of (one-of (turtles-at 1 0))) decelerate ] [ ifelse (look-ahead = 2) [ ifelse (any? turtles-at 2 0) [ set speed ([speed] of (one-of turtles-at 2 0)) decelerate ] [ accelerate if count turtles-at 0 1 = 0 and ycor < 2.5 [lt 90 fd 1 rt 90] ] ] [accelerate if count turtles-at 0 1 = 0 and ycor < 2.5 [lt 90 fd 1 rt 90] ] ] if (speed < 0.01) [ set speed 0.01 ] if (speed > speed-limit) [ set speed speed-limit ] ifelse (change? = false) [ signal ] [ change-lanes ] ;; Control for making sure no one crashes. ifelse (any? turtles-at 1 0) and (xcor != min-pxcor - .5) [ set speed [speed] of (one-of turtles-at 1 0) ] [ ifelse ((any? turtles-at 2 0) and (speed > 1.0)) [ set speed ([speed] of (one-of turtles-at 2 0)) fd 1 ] [jump speed] ] ] tick end ;; increase speed of cars to accelerate ;; turtle procedure set speed (speed + (speed-up / 1000)) end ;; reduce speed of cars to decelerate ;; turtle procedure set speed (speed - (slow-down / 1000)) end to signal ifelse (any? turtles-at 1 0) [ if ([speed] of (one-of (turtles-at 1 0))) < (speed) [ set change? true ] ] [ set change? false ] end ;; undergoes search algorithms to change-lanes ;; turtle procedure show ycor ifelse (patience <= 0) [ ifelse (max-patience <= 1) [ set max-patience (random 10) + 1 ] [ set max-patience (max-patience - (random 5)) ] set patience max-patience ifelse (target-lane = 0) [ set target-lane 1 set lane 0 ] [ set target-lane 0 set lane 1 ] ] [ set patience (patience - 1) ] ifelse (target-lane = lane) [ ifelse (target-lane = 0) [ set target-lane 1 set change? false ] [ set target-lane 0 set change? false ] ] [ ifelse (target-lane = 1) [ ifelse (pycor = 2) [ set lane 1 set change? false ] [ ifelse (not any? turtles-at 0 1) [ set ycor (ycor + 1) ] [ ifelse (not any? turtles-at 1 0) [ set xcor (xcor + 1) ] [ decelerate if (speed <= 0) [ set speed 0.1 ] ] ] ] ] [ ifelse (pycor = -2) [ set lane 0 set change? false ] [ ifelse (not any? turtles-at 0 -1) [ set ycor (ycor - 1) ] [ ifelse (not any? turtles-at 1 0) [ set xcor (xcor + 1) ] [ decelerate if (speed <= 0) [ set speed 0.1 ] ] ] ] ] ] end I know its a bit messy because I am using code from other models from the library. I want to know how to create the collision of the cars. I can't think of any idea. As you notice my agent has almost the same size as the patch (I set it to 0.9 so that you can distinguish the space between 2 cars when they are set next to each other and I round the coordinates so that they are set to the centre of the patch). In my accelerate procedure I set my agent to turn left, move 1, turn right in a loop. I want to know if there's a command that lets me make the agent jump from one lane to the other (to the patch next to it on its left) without making it turn and move. And last, if you notice the code i created the car checks the patch that is next to it on the lane on its left and the patch in front of it and the back of it. So if the 3 patches on its left are empty then it can change lane. The fuzzy part is that when i run the setup and I press Go sometimes (not always) the car goes out of the 3 basic lanes. To understand this I have 7 lanes. The middle one which I don't use which is lane 0. Then there are 3 lanes on top of lane 0 and 3 below it. So the code I am using refers to the upper 3 lanes where I set the cars but for some reason some of the cars change lane and go to lane -3 then -2 and so forth. If someone can give me a tip I would really appreciate it. Thank you in advance. Tip: if you want to try this code in netlogo keep in mind that on interface tab I have 2 buttons one setup and one go as well as 3 sliders with names: number_of_cars , speed-up , slow-down.

    Read the article

  • Reading a user input (character or string of letters) into ggplot command inside a switch statement or a nested ifelse (with functions in it)

    - by statisticalbeginner
    I have code like AA <- as.integer(readline("Select any number")) switch(AA, 1={ num <-as.integer(readline("Select any one of the options \n")) print('You have selected option 1') #reading user data var <- readline("enter the variable name \n") #aggregating the data based on required condition gg1 <- aggregate(cbind(get(var))~Mi+hours,a, FUN=mean) #Ploting ggplot(gg1, aes(x = hours, y = get(var), group = Mi, fill = Mi, color = Mi)) + geom_point() + geom_smooth(stat="smooth", alpha = I(0.01)) }, 2={ print('bar') }, { print('default') } ) The dataset is [dataset][1] I have loaded the dataset into object list a <- read.table(file.choose(), header=FALSE,col.names= c("Ei","Mi","hours","Nphy","Cphy","CHLphy","Nhet","Chet","Ndet","Cdet","DON","DOC","DIN","DIC","AT","dCCHO","TEPC","Ncocco","Ccocco","CHLcocco","PICcocco","par","Temp","Sal","co2atm","u10","dicfl","co2ppm","co2mol","pH")) I am getting error like source ("switch_statement_check.R") Select any one of the options 1 [1] "You have selected option 1" enter the variable name Nphy Error in eval(expr, envir, enclos) : (list) object cannot be coerced to type 'double' > gg1 is getting data that is fine. I dont know what to do to make the variable entered by user to work in that ggplot command. Please suggest any solution for this. The dput output structure(list(Ei = c(1L, 1L, 1L, 1L, 1L, 1L), Mi = c(1L, 1L, 1L, 1L, 1L, 1L), hours = 1:6, Nphy = c(0.1023488, 0.104524, 0.1064772, 0.1081702, 0.1095905, 0.110759), Cphy = c(0.6534707, 0.6448216, 0.6369597, 0.6299084, 0.6239005, 0.6191941), CHLphy = c(0.1053458, 0.110325, 0.1148174, 0.1187672, 0.122146, 0.1249877), Nhet = c(0.04994161, 0.04988347, 0.04982555, 0.04976784, 0.04971029, 0.04965285), Chet = c(0.3308593, 0.3304699, 0.3300819, 0.3296952, 0.3293089, 0.3289243), Ndet = c(0.04991916, 0.04984045, 0.04976363, 0.0496884, 0.04961446, 0.04954156), Cdet = c(0.3307085, 0.3301691, 0.3296314, 0.3290949, 0.3285598, 0.3280252), DON = c(0.05042275, 0.05085697, 0.05130091, 0.05175249, 0.05220978, 0.05267118 ), DOC = c(49.76304, 49.52745, 49.29323, 49.06034, 48.82878, 48.59851), DIN = c(14.9933, 14.98729, 14.98221, 14.9781, 14.97485, 14.97225), DIC = c(2050.132, 2050.264, 2050.396, 2050.524, 2050.641, 2050.758), AT = c(2150.007, 2150.007, 2150.007, 2150.007, 2150.007, 2150.007), dCCHO = c(0.964222, 0.930869, 0.8997098, 0.870544, 0.843196, 0.8175117), TEPC = c(0.1339044, 0.1652179, 0.1941872, 0.2210289, 0.2459341, 0.2690721), Ncocco = c(0.1040715, 0.1076058, 0.1104229, 0.1125141, 0.1140222, 0.1151228), Ccocco = c(0.6500288, 0.6386706, 0.6291149, 0.6213265, 0.6152447, 0.6108502), CHLcocco = c(0.1087667, 0.1164099, 0.1225822, 0.1273103, 0.1308843, 0.1336465), PICcocco = c(0.1000664, 0.1001396, 0.1007908, 0.101836, 0.1034179, 0.1055634), par = c(0, 0, 0.8695131, 1.551317, 2.777707, 4.814341), Temp = c(9.9, 9.9, 9.9, 9.9, 9.9, 9.9), Sal = c(31.31, 31.31, 31.31, 31.31, 31.31, 31.31), co2atm = c(370, 370, 370, 370, 370, 370), u10 = c(0.01, 0.01, 0.01, 0.01, 0.01, 0.01), dicfl = c(-2.963256, -2.971632, -2.980446, -2.989259, -2.997877, -3.005702), co2ppm = c(565.1855, 565.7373, 566.3179, 566.8983, 567.466, 567.9814), co2mol = c(0.02562326, 0.02564828, 0.0256746, 0.02570091, 0.02572665, 0.02575002 ), pH = c(7.879427, 7.879042, 7.878636, 7.878231, 7.877835, 7.877475)), .Names = c("Ei", "Mi", "hours", "Nphy", "Cphy", "CHLphy", "Nhet", "Chet", "Ndet", "Cdet", "DON", "DOC", "DIN", "DIC", "AT", "dCCHO", "TEPC", "Ncocco", "Ccocco", "CHLcocco", "PICcocco", "par", "Temp", "Sal", "co2atm", "u10", "dicfl", "co2ppm", "co2mol", "pH"), row.names = c(NA, 6L), class = "data.frame") As per the below suggestions I have tried a lot but it is not working. Summarizing I will say: var <- readline("enter a variable name") I cant use get(var) inside any command but not inside ggplot, it wont work. gg1$var it also doesnt work, even after changing the column names. Does it have a solution or should I just choose to import from an excel sheet, thats better? Tried with if else and functions fun1 <- function() { print('You have selected option 1') my <- as.character((readline("enter the variable name \n"))) gg1 <- aggregate(cbind(get(my))~Mi+hours,a, FUN=mean) names(gg1)[3] <- my #print(names(gg1)) ggplot (gg1,aes_string(x="hours",y=(my),group="Mi",color="Mi")) + geom_point() } my <- as.integer(readline("enter a number")) ifelse(my == 1,fun1(),"") ifelse(my == 2,print ("its 2"),"") ifelse(my == 3,print ("its 3"),"") ifelse(my != (1 || 2|| 3) ,print("wrong number"),"") Not working either...:(

    Read the article

  • How do I write an IF ELSE to check string contents of an array?

    - by Michael Robinson
    I'm trying to write an IF ELSE statement to enable shipping, If user doesn't add an address the array contents remain as "-" & "-" for the two items in the array. I want to check to see if those are in the array, if they are then I want to enableshipping. Here is the code for getting the array: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/arraySaveFile", documentsDirectory]; NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName]; How do I write this first line to look for the "-" & "-"? if ([fullFileName isEqualToString:@"-","-"]) { [nnNEP EnableShipping]; } else { [nnNEP DisableShipping]; } Thanks, michael

    Read the article

  • Need some help with onClick and an if/else issue...

    - by Adam
    I have a menu with seven items. If you click the first item, div one shows. If you click any other item (2 through 7) div two shows. That's what I'm looking to do. I'm new at all this but am pretty sure it's an if/else function, such that if I click on <a id="1">, show the first div, else show the second div. I suppose I can do a hide/show to get back to the first div. I'm going to keep poking around, but if I can't find it, any help is surely appreciated.

    Read the article

  • Batch file: Extracting substring from input parameter to use in IF statement

    - by Neomoon
    This is a very basic example of what I am trying to implement in a more complex batch file. I would like to extract a substring from an input parameter (%1) and branch based on if the substring was found or not. @echo off SETLOCAL enableextensions enabledelayedexpansion SET _testvariable=%1 SET _testvariable=%_testvariable:~4,3% ECHO %_testvariable% IF %_testvariable%=act CALL :SOME IF NOT %_testvariable%=act CALL :ACTION :SOME ECHO Substring found GOTO :END :ACTION ECHO Substring not found GOTO :END ENDLOCAL :END This is what my ouput looks like: C:\>test someaction act =act was unexpected at this time. If possible I would like to turn this in to a IF/ELSE statement and evaluate directly from %1. However I have not had success with either.

    Read the article

  • I want to use contents of String or Array in an IF ELSE statement for iphone

    - by Michael Robinson
    I want to check to see if an array is empty to activate a shipping method. Here is the code for returning the array. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/arraySaveFile", documentsDirectory]; NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName]; I want to write something like: if NSString *fullFileName ="" ; [nnNEP EnableShipping]; else [nnNEP DisableShipping]; OR if array contents ="" ; [nnNEP EnableShipping]; else [nnNEP DisableShipping]; I just can't find the right or description on how to do this properly. Thanks,

    Read the article

  • R how to find NA values after using addNA function

    - by screechOwl
    I have a data frame with a bunch of categorical variables. Some of them contain NA's and I use the addNA function to convert them to an explicit factor level. My problem comes when I try to treat them as NA's they don't seem to register. Here's my example data set and attempts to 'find' NA's: df1 <- data.frame(id = 1:200, y =rbinom(200, 1, .5), var1 = factor(rep(c('abc','def','ghi','jkl'),50))) df1$var2 <- factor(rep(c('ab c','ghi','jkl','def'),50)) df1$var3 <- factor(rep(c('abc','ghi','nop','xyz'),50)) df1[df1$var1 == 'abc','var1'] <- NA df1$var1 <- addNA(df1$var1) df1$isNaCol <- ifelse(df1$var1 == NA, 1, 0);summary(df1$isNaCol) df1$isNaCol <- ifelse(is.na(df1$var1), 1, 0);summary(df1$isNaCol) df1$isNaCol <- ifelse(df1$var1 == 'NA', 1, 0);summary(df1$isNaCol) df1$isNaCol <- ifelse(df1$var1 == '<NA>', 1, 0);summary(df1$isNaCol) Also when I type ??addNA I don't get any matches. Is this a gray-market function or something? Any suggestions would be appreciated.

    Read the article

  • R: Plotting a graph with different colors of points based on advanced criteria

    - by balconydoor
    What I would like to do is a plot (using ggplot), where the x axis represent years which have a different colour for the last three years in the plot than the rest. The last three years should also meet a certain criteria and based on this the last three years can either be red or green. The criteria is that the mean of the last three years should be less (making it green) or more (making it red) than the 66%-percentile of the remaining years. So far I have made two different functions calculating the last three year mean: LYM3 <- function (x) { LYM3 <- tail(x,3) mean(LYM3$Data,na.rm=T) } And the 66%-percentile for the remaining: perc66 <- function(x) { percentile <- head(x,-3) quantile(percentile$Data, .66, names=F,na.rm=T) } Here are two sets of data that can be used in the calculations (plots), the first which is an example from my real data where LYM3(df1) < perc66(df1) and the second is just made up data where LYM3 perc66. df1<- data.frame(Year=c(1979:2010), Data=c(347261.87, 145071.29, 110181.93, 183016.71, 210995.67, 205207.33, 103291.78, 247182.10, 152894.45, 170771.50, 206534.55, 287770.86, 223832.43, 297542.86, 267343.54, 475485.47, 224575.08, 147607.81, 171732.38, 126818.10, 165801.08, 136921.58, 136947.63, 83428.05, 144295.87, 68566.23, 59943.05, 49909.08, 52149.11, 117627.75, 132127.79, 130463.80)) df2 <- data.frame(Year=c(1979:2010), Data=c(sample(50,29,replace=T),75,75,75)) Here’s my code for my plot so far: plot <- ggplot(df1, aes(x=Year, y=Data)) + theme_bw() + geom_point(size=3, aes(colour=ifelse(df1$Year<2008, "black",ifelse(LYM3(df1) < perc66(df1),"green","red")))) + geom_line() + scale_x_continuous(breaks=c(1980,1985,1990,1995,2000,2005,2010), limits=c(1978,2011)) plot As you notice it doesn’t really do what I want it to do. The only thing it does seem to do is that it turns the years before 2008 into one level and those after into another one and base the point colour off these two levels. Since I don’t want this year to be stationary either, I made another tiny function: fun3 <- function(x) { df <- subset(x, Year==(max(Year)-2)) df$Year } So the previous code would have the same effect as: geom_point(size=3, aes(colour=ifelse(df1$Year<fun3(df1), "black","red"))) But it still does not care about my colours. Why does it make the years into levels? And how come an ifelse function doesn’t work within another one in this case? How would it be possible to the arguments to do what I like? I realise this might be a bit messy, asking for a lot at the same time, but I hope my description is pretty clear. It would be helpful if someone could at least point me in the right direction. I tried to put the code for the plot into a function as well so I wouldn’t have to change the data frame at all functions within the plot, but I can’t get it to work. Thank you!

    Read the article

  • Replace values in a dataframe based on another factor which contains NA's in R

    - by PaulHurleyuk
    I have a dataframe which contains (among other things) a numeric column with a concentration, and a factor column with a status flag. This status flag contains NA's. Here's an example df<-structure(list(conc = c(101.769, 1.734, 62.944, 92.697, 25.091, 27.377, 24.343, 55.084, 0.335, 23.280), status = structure(c(NA, NA, NA, NA, NA, NA, 2L, NA, 1L, NA), .Label = c("<LLOQ", "NR"), class = "factor")), .Names = c("conc", "status"), row.names = c(NA, -10L), class = "data.frame") I want to replace the concentration column with a string for some values of the flag column, or with the concentration value formatted to a certain number of significant digits. When I try this ifelse(df$status=="NR","NR",df$conc) The NA's in the status flag don't trigger either the true or false condition (and return NA) - as the documentation suggests it will. I could loop over the rows and use IF then else on each one but this seems inefficient. Am I missing something ? I've tried as.character(df$status) as well which doesn't work. My mojo must be getting low....

    Read the article

  • Netlogo Programming question - Chemical Equilibrium temperature and pressure implementation

    - by user286190
    Hi I am trying to code something in Netlogo..I am using an existing model Chemical Equilibrium and am trying to implement the following: turtles-own [speed ] ask turtles [ ;; set velocity ( ambient-temperature = 30 ) ;; fd velocity if temp > 40 [ "speed" increases of turtles ] ifelse temperature < 30 [ speed of turtles decreases] ] ;; to temp but it does not seem to work (it temperature is more than 40 the speed of the turtles increases if the temperature is less than 30 the speed of the turtles decreases) temperature is a slider on the model the same for pressure ask turtles [ ;; if pressure > 50 then speed increases of turtles ;; if pressure < 50 then speed decreases of turtles ] ;; to pressure thanks

    Read the article

  • Binning a numeric variable in R

    - by McPeterson
    I have a vector X that contains positive numbers that I want to bin/discretize. For this vector, I want the numbers [0, 10) to show up just as they exist in the vector, but numbers [10,∞) to be 10+. I'm using: x <- c(0,1,3,4,2,4,2,5,43,432,34,2,34,2,342,3,4,2) binned.x <- as.factor(ifelse(x > 10,"10+",x)) but this feels klugey to me. Does anyone know a better solution or a different approach? mcpeterson

    Read the article

  • How to Import a CSV file containing multiple sections into R?

    - by PaulHurleyuk
    I want to import the contents of a csv file into R, the csv file contains multiple sections of data vertically, seperated by blank lines and asterisks. For example ******************************************************** * SAMPLE DATA ****************************************** ******************************************************** Name, DOB, Sex Rod, 1/1/1970, M Jane, 5/7/1980, F Freddy, 9.12,1965, M ******************************************************* * Income Data **************************************** ******************************************************* Name, Income Rod, 10000 Jane, 15000 Freddy, 7500 I would like to import this into R as two seperate dataframes. Currently I'm manually cutting the csv file up into smaller files, but I think I could do it using read.csv and the skip and nrows settings of read.csv, If I could work out where the secion breaks are. This gives me a logical TRUE for every blank line ifelse(readLines("DATA.csv")=="",TRUE,FALSE) I'm hoping someone has already solved this problem.

    Read the article

  • Handling missing/incomplete data in R

    - by doug
    As you would expect from a DSL aimed at data analysts, R handles missing/incomplete data very well, for instance: Many R functions have an 'na.rm' flag that you can set to 'T' to remove the NAs, but if you want to deal with this before the function call, then: to replace each 'NA' w/ 0: ifelse(is.na(vx), 0, vx) to remove each 'NA': vx = vx[!is.na(a)] to remove entire each row that contains 'NA' from a data frame: dfx = dfx[complete.cases(dfx),] All of these functions remove 'NA' or rows with an 'NA' in them. Sometimes this isn't quite what you want though--making an 'NA'-excised copy of the data frame might be necessary for the next step in the workflow but in subsequent steps you often want those rows back (e.g., to calculate a column-wise statistic for a column that has missing rows caused by a prior call to 'complete cases' yet that column has no 'NA' values in it). to be as clear as possible about what i'm looking for: python/numpy has a class, 'masked array', with a 'mask' method, which lets you conceal--but not remove--NAs during a function call. Is there an analogous function in R?

    Read the article

  • How to make sure the value is reset in foreach loop in PHP

    - by kwokwai
    Hi all, I was writing a simple PHP page and a few foreach loops were used. Here are the scripts: $arrs = array("a", "b", "c"); foreach ($arrs as $arr) { if(substr($arr,0,1)=="b") { echo "This is b"; } } // ends of first foreach loop and I didn't use ifelse here And when this foreach ends, I wrote another foreach loop in which all the values in the foreach loop was the same as previous foreach. foreach ($arrs as $arr) { if(substr($arr,0,1)=="c") { echo "This is c"; } } I am not sure if it is a good practice to have two foreach loops with same values and keys. Will the values get overwritten in the first foreach loop?

    Read the article

  • compare two characters based on subset

    - by schultem
    I have a simple dataframe with two columns: df <- data.frame(x = c(1,1,2,2,3), y = c(rep(1:2,2),1), target = c('a','a','a','b','a')) I would like to compare the strings in the target column (find out whether they are equal or not, i.e., TRUE or FALSE) within every level of x (same number for x). First I would like to compare lines 1 and 2, then 3 and 4 ... My problem is that I am missing some comparisons, for example, line 5 has only one case instead of two - so it should turn out to be FALSE. Variable y indicates the first and second case within x. I played around with ddply doing something like: ddply(df, .(x), summarise, ifelse(as.character(df[df$y == '1',]$target), as.character(df[df$y == '2',]$target),0,1)) which is ugly ... and does not work ... Any insights how I could achieve this comparison? Thanks

    Read the article

  • Adding trend lines/boxplots (by group) in ggplot2

    - by Tal Galili
    Hi all, I have 40 subjects, of two groups, over 15 weeks, with some measured variable (Y). I wish to have a plot where: x = time, y = T, lines are by subjects and colours by groups. I found it can be done like this: TIME <- paste("week",5:20) ID <- 1:40 GROUP <- sample(c("a","b"),length(ID), replace = T) group.id <- data.frame(GROUP, ID) a <- expand.grid(TIME, ID) colnames(a) <-c("TIME", "ID") group.id.time <- merge(a, group.id) Y <- rnorm(dim(group.id.time)[1], mean = ifelse(group.id.time$GROUP =="a",1,3) ) DATA <- cbind(group.id.time, Y) qplot(data = DATA, x=TIME, y=Y, group=ID, geom = c("line"),colour = GROUP) But now I wish to add to the plot something to show the difference between the two groups (for example, a trend line for each group, with some CI shadelines) - how can it be done? I remember once seeing the ggplot2 can (easily) do this with geom_smooth, but I am missing something about how to make it work. Also, I wondered at maybe having the lines be like a boxplot for each group (with a line for the different quantiles and fences and so on). But I imagine answering the first question would help me resolve the second. Thanks.

    Read the article

  • pdfmark for docinfo metadata in pdf is not accepting accented characters in Keywords or Subject

    - by rpilkey
    I am inserting metadata into postscript files with a program, to be distilled to pdf with Adobe Distiller. I am using this code that I grabbed from Thomas Merz's "Web Publishing with Acrobat-PDF": /pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse [ /Title (mot accenté) /Author (mot accenté) /Subject (mot accenté) /Keywords (mot accenté) /DOCINFO pdfmark When you look at the metadata, the accented characters turn into "?" in the Subject and Keyword fields, but not the Title and Author fields. The characters are the same ascii 233 I tried replacing them with octal encoding (\351), which came out the same (Title and Author okay, Subject and Keywords messed up). file encoding is latin-1,unix eol I found a mention on adobe forums, but the answer didn't make sense to me. http://forums.adobe.com/message/1165593 I changed the encoding to utf-8, inserted the characters binarily (in VIM : <Ctrl-v>u00e9), no change. I tried inserting the BOM in a few places, it didn't work. This is with Acrobat Pro 9 I didn't notice this problem with Acrobat Pro 7. Does anybody know of a workaround to get the accented characters into ALL the metadata fields when modifying a postscript file, or tell me if I'm doing it wrong? It seems weird that different fields would not accept the same bytes.

    Read the article

  • Handling missing/incomplete data in R--is there function to mask but not remove NAs?

    - by doug
    As you would expect from a DSL aimed at data analysis, R handles missing/incomplete data very well, for instance: Many R functions have an 'na.rm' flag that you can set to 'T' to remove the NAs: mean( c(5,6,12,87,9,NA,43,67), na.rm=T) But if you want to deal with NAs before the function call, you need to do something like this: to remove each 'NA' from a vector: vx = vx[!is.na(a)] to remove each 'NA' from a vector and replace it w/ a '0': ifelse(is.na(vx), 0, vx) to remove entire each row that contains 'NA' from a data frame: dfx = dfx[complete.cases(dfx),] All of these functions permanently remove 'NA' or rows with an 'NA' in them. Sometimes this isn't quite what you want though--making an 'NA'-excised copy of the data frame might be necessary for the next step in the workflow but in subsequent steps you often want those rows back (e.g., to calculate a column-wise statistic for a column that has missing rows caused by a prior call to 'complete cases' yet that column has no 'NA' values in it). to be as clear as possible about what i'm looking for: python/numpy has a class, 'masked array', with a 'mask' method, which lets you conceal--but not remove--NAs during a function call. Is there an analogous function in R?

    Read the article

  • Scripting custom drawing in Delphi application with IF/THEN/ELSE statements?

    - by Jerry Dodge
    I'm building a Delphi application which displays a blueprint of a building, including doors, windows, wiring, lighting, outlets, switches, etc. I have implemented a very lightweight script of my own to call drawing commands to the canvas, which is loaded from a database. For example, one command is ELP 1110,1110,1290,1290,3,8388608 which draws an ellipse, parameters are 1110x1110 to 1290x1290 with pen width of 3 and the color 8388608 converted from an integer to a TColor. What I'm now doing is implementing objects with common drawing routines, and I'd like to use my scripting engine, but this calls for IF/THEN/ELSE statements and such. For example, when I'm drawing a light, if the light is turned on, I'd like to draw it yellow, but if it's off, I'd like to draw it gray. My current scripting engine has no recognition of such statements. It just accepts simple drawing commands which correspond with TCanvas methods. Here's the procedure I've developed (incomplete) for executing a drawing command on a canvas: function DrawCommand(const Cmd: String; var Canvas: TCanvas): Boolean; type TSingleArray = array of Single; var Br: TBrush; Pn: TPen; X: Integer; P: Integer; L: String; Inst: String; T: String; Nums: TSingleArray; begin Result:= False; Br:= Canvas.Brush; Pn:= Canvas.Pen; if Assigned(Canvas) then begin if Length(Cmd) > 5 then begin L:= UpperCase(Cmd); if Pos(' ', L)> 0 then begin Inst:= Copy(L, 1, Pos(' ', L) - 1); Delete(L, 1, Pos(' ', L)); L:= L + ','; SetLength(Nums, 0); X:= 0; while Pos(',', L) > 0 do begin P:= Pos(',', L); T:= Copy(L, 1, P - 1); Delete(L, 1, P); SetLength(Nums, X + 1); Nums[X]:= StrToFloatDef(T, 0); Inc(X); end; Br.Style:= bsClear; Pn.Style:= psSolid; Pn.Color:= clBlack; if Inst = 'LIN' then begin Pn.Width:= Trunc(Nums[4]); if Length(Nums) > 5 then begin Br.Style:= bsSolid; Br.Color:= Trunc(Nums[5]); end; Canvas.MoveTo(Trunc(Nums[0]), Trunc(Nums[1])); Canvas.LineTo(Trunc(Nums[2]), Trunc(Nums[3])); Result:= True; end else if Inst = 'ELP' then begin Pn.Width:= Trunc(Nums[4]); if Length(Nums) > 5 then begin Br.Style:= bsSolid; Br.Color:= Trunc(Nums[5]); end; Canvas.Ellipse(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3])); Result:= True; end else if Inst = 'ARC' then begin Pn.Width:= Trunc(Nums[8]); Canvas.Arc(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3]), Trunc(Nums[4]),Trunc(Nums[5]),Trunc(Nums[6]),Trunc(Nums[7])); Result:= True; end else if Inst = 'TXT' then begin Canvas.Font.Size:= Trunc(Nums[2]); Br.Style:= bsClear; Pn.Style:= psSolid; T:= Cmd; Delete(T, 1, Pos(' ', T)); Delete(T, 1, Pos(',', T)); Delete(T, 1, Pos(',', T)); Delete(T, 1, Pos(',', T)); Canvas.TextOut(Trunc(Nums[0]), Trunc(Nums[1]), T); Result:= True; end; end else begin //No space found, not a valid command end; end; end; end; What I'd like to know is what's a good lightweight third-party scripting engine I could use to accomplish this? I would hate to implement parsing of IF, THEN, ELSE, END, IFELSE, IFEND, and all those necessary commands. I need simply the ability to tell the scripting engine if certain properties meet certain conditions, it needs to draw the object a certain way. The light example above is only one scenario, but the same solution needs to also be applicable to other scenarios, such as a door being open or closed, locked or unlocked, and draw it a different way accordingly. This needs to be implemented in the object script drawing level. I can't hard-code any of these scripting/drawing rules, the drawing needs to be controlled based on the current state of the object, and I may also wish to draw a light a certain shade or darkness depending on how dimmed the light is.

    Read the article

  • PHP HTML CSS Beginner USE CASE / SWITCH / IF ELSE? Need advice...

    - by WANNABE
    Building a website using a PHP based Ecommerce product Magnto. The problem I have is that I want to use tabbed navigation. My idea was to use CSS to show the TAB over the relevant Navigation menu item based on the URL. However, one URL always changes, so I wanted to somehow use an ifelse statement. I've come up with two methods that I think could work, could any experts tell me what they would think is best and how they would implement it? <div id="nav"> <ul id="mainnav"> <li><a href="index.php" title="Welcome page" <?php if ($page == 'index.php') { ?>class="active"<?php } ?>>Welcome</a></li> <li><a href="about_us.php" title="About us page" <?php if ($page == 'about_us.php') { ?>class="active"<?php } ?>>About us</a></li> <li><a href="services.php" title="Services page" <?php if ($page == 'services.php') { ?>class="active"<?php } ?>>Services</a></li> <li><a href="testimonials.php" title="Testimonials page" <?php if ($page == 'testimonials.php') { ?>class="active"<?php } ?>>Testimonials</a></li> <li><a href="contact_us.php" title="Contact us page" <?php if ($page == 'contact_us.php') { ?>class="active"<?php } ?>>Contact us</a></li> else <li><a href="store.php" title="Store Page" <?php ($page == 'store.php') { ?>class="active"<?php } ?>>Store</a></li> </ul> </div> $URL = store.php; SWITCH ($sample) { CASE home.php: <li><a href="index.php" title="Welcome page" <?php if ($page == 'index.php') { ?>class="active"<?php } ?>>Welcome</a></li> break; CASE services.php: <li><a href="services.php" title="Services page" <?php if ($page == 'services.php') { ?>class="active"<?php } ?>>Services</a></li> break; CASE aboutus.php: <li><a href="about_us.php" title="About us page" <?php if ($page == 'about_us.php') { ?>class="active"<?php } ?>>About us</a></li> break; DEFAULT: <li><a href="store.php" title="Store Page" <?php ($page == 'store.php') { ?>class="active"<?php } ?>>Store</a></li> } Thanks in advance

    Read the article

1