Wednesday, 15 July 2015

if statement - Subsetting data in R with ifelse -



if statement - Subsetting data in R with ifelse -

i attempting utilize ifelse subset info can used in plot. coding way trying create code usable layman defining 1 or 2 objects , running whole script create plot using info selected given criteria.

the problem mydataframe[mydataframe$data . ...] operation not working way within ifelse. there way work in ifelse or aware of smarter way i'm trying do? thanks!

also, sec block of code added explanation not needed see problem.

# generate info mydata<-c(1:100) mydata<-as.data.frame(mydata) mydata$checkthefunction<-rep(c("one","two","three","four","multiple of 5", "six","seven","eight","nine","multiple of 10")) # looks right mydata # create function myfunction = function(mycondition="low"){ # special criteria lowrandomnumbers=c(58,61,64,69,73) highrandomnumbers=c(78,82,83,87,90) # subset info based on mycondition mydata<-ifelse(mycondition=="low",mydata[mydata$mydata %in% lowrandomnumbers==true,],mydata) mydata<-ifelse(mycondition=="high",mydata[mydata$mydata %in% highrandomnumbers==true,],mydata) # if not "high" or "low" don't subset info mydata } myfunction("low") # returns numbers selected dataframe, not # subsetted dataframe $checkthefunction row myfunction("high") # returns: "error in mydata[mydata$mydata %in% highrandomnumbers == true, ] : # wrong number of dimensions" # additional explanation code if helps # define dataframe 1 time again mydata<-c(1:100) mydata<-as.data.frame(mydata) mydata$checkthefunction<-rep(c("one","two","three","four","multiple of 5", "six","seven","eight","nine","multiple of 10")) # outside of function , ifelse subsetting works lowrandomnumbers=c(58,61,64,69,73) itworks<-mydata[mydata$mydata %in% lowrandomnumbers==true,] # ifelse seems problem, dataframe cutting string of lowrandomnumbers 1 time again mycondition="low" noluck<-ifelse(mycondition=="low",mydata[mydata$mydata %in% lowrandomnumbers==true,],mydata) noluck # if 'else' portion returned dataframe converted one-dimensional list mycondition="high" noluck<-ifelse(mycondition=="low",mydata[mydata$mydata %in% lowrandomnumber==true,mydata) noluck

you don't want ifelse. want if , else. ifelse used if have status vector. have single status value.

myfunction = function(mycondition="low"){ # special criteria lowrandomnumbers=c(58,61,64,69,73) highrandomnumbers=c(78,82,83,87,90) # subset info based on mycondition mydata <- if(mycondition=="low") mydata[mydata$mydata %in% lowrandomnumbers==true,] else mydata mydata <- if(mycondition=="high") mydata[mydata$mydata %in% highrandomnumbers==true,] else mydata # if not "high" or "low" don't subset info mydata }

r if-statement subset

No comments:

Post a Comment