2014-06-18 6 views
1

ifelse를 사용하여 플롯에서 사용할 수있는 데이터의 하위 집합을 만들려고합니다. 하나 또는 두 개의 객체 만 정의하고 주어진 스크립트를 실행하여 주어진 기준에 따라 선택된 데이터를 사용하여 플롯을 작성함으로써 평신도에게 코드를 유용하게 만들기 위해이 방법으로 코딩하고 있습니다.ifelse를 사용하여 R로 데이터 채우기

문제는 mydataframe [mydataframe $ data. ...] 작업이 내가 원하는대로 작동하지 않습니다. ifelse에서 작동하도록 할 수있는 방법이 있습니까? 아니면 내가하려는 일을 더 똑똑한 방법으로 알고있는 사람이 있습니까? 감사!

또한 두 번째 코드 블록에는 설명이 추가되었지만 문제를 확인하는 데는 필요하지 않습니다.

# generate data 
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")) 
# everything 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 the data 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" then don't subset the data 

    mydata 
} 

myfunction("low") 
# returns just the numbers selected from the dataframe, not the 
# subsetted dataframe with the $checkthefunction row 

myfunction("high") 
# returns: "Error in mydata[mydata$mydata %in% highRandomNumbers == TRUE, ] : 
# incorrect number of dimensions" 









# additional explanation code if it helps 

# define dataframe 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 the function and ifelse my subsetting works 
lowRandomNumbers=c(58,61,64,69,73) 
ItWorks<-mydata[mydata$mydata %in% lowRandomNumbers==TRUE,] 

# ifelse seems to be the problem, the dataframe is cut into the string of lowRandomNumbers again 
MyCondition="low" 
NoLuck<-ifelse(MyCondition=="low",mydata[mydata$mydata %in% lowRandomNumbers==TRUE,],mydata) 
NoLuck 

# if the 'else' portion is returned the dataframe is converted to a one-dimensional list 
MyCondition="high" 
NoLuck<-ifelse(MyCondition=="low",mydata[mydata$mydata %in% lowRandomNumber==TRUE,mydata) 
NoLuck    
+0

예상보다 쉬운 수정이었습니다. 감사! – user3745597

+0

@Roland if와 else를 사용하면 else에서 조건 중 하나라도 충족되지 않으면 데이터 프레임을 변경하지 않아야합니까? 또는 'if'조건이 충족되지 않으면 R이 자동으로 데이터 프레임을 변경하지 않습니까? – user3745597

답변

4

ifelse을 원하지 않습니다. ifelse이 필요합니다. 조건 벡터가있는 경우 ifelse이 사용됩니다. 단일 조건 값만 있습니다.

myfunction = function(MyCondition="low"){ 

    # special criteria 
    lowRandomNumbers=c(58,61,64,69,73) 
    highRandomNumbers=c(78,82,83,87,90) 
    # subset the data 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" then don't subset the data 

    mydata 
} 
관련 문제