【发布时间】:2014-06-18 14:56:00
【问题描述】:
我正在尝试使用 ifelse 来对可以在绘图中使用的数据进行子集化。我之所以这样编码,是因为我试图通过仅定义一个或两个对象然后运行整个脚本以使用由给定标准选择的数据制作绘图来使代码可供外行使用。
问题在于 mydataframe[mydataframe$data 。 ...] 操作无法按照我希望的方式在 ifelse 中运行。有没有办法让它在 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
【问题讨论】:
-
嗯,这比我预期的更容易解决,它有效。谢谢!
-
@Roland 使用 if 和 else 我是否必须在 else 中指定如果不满足任何条件则不要更改数据框?或者如果不满足“if”条件,R 会不会自动更改数据帧?
标签: r if-statement subset