[R] How to replace some output candidates in a function?
Atte Tenkanen
attenka at utu.fi
Fri Mar 24 23:22:34 CET 2006
Hello,
I have a function called "prime form" (here below). It works mostly ok,
but some of the output vectors it gives are not those I want. For example,
if the result (Pf) in the end is c(0,2,3,7,8) I'd like to replace it with
the vector c(0,1,5,7,8) and there are appr. 20 other cases. How to make
those corrections in the end of the algorithm before "return(Pf)"?
I know this works...
if (identical(Pf,c(0,2,3,7,8))){Pf=c(0,1,5,7,8)}
if (identical(Pf,c(0,2,5,6,9))){Pf=c(0,1,4,7,9)}
.
.
.
... but is there some more elegant way?
##*****************************##
## Function primeform (pform) ##
##*****************************##
# INPUT:string of pitch class numbers.
# USAGE: pform(c(1,4,8,9,0,4)).
pform=function(spcn)
{
if(length(spcn)==1) # if the length of the pcs is 1,
# then the prime form is c(0)
{
Pf=c(0)
} else
{
spcno=sort(unique(spcn));# sort & lop duplicates
succ_i_arr=c() # create successive interval array
succ_i_arr[length(spcno)]=(spcno[1]+12)-spcno[length(spcno)]
for(i in 2:length(spcno))
{
succ_i_arr[i-1]=spcno[i]-spcno[i-1]
}
m=matrix(nrow=length(succ_i_arr),ncol=length(succ_i_arr))
for(i in 1:length(succ_i_arr)) # matrix of possible
alternatives
{
m[,i]=succ_i_arr
succ_i_arr=c(succ_i_arr[length(succ_i_arr)],succ_i_arr[2:length(succ_i_arr)-1])
}
b=0
for(i in 1:length(m[1,]))
{
b[i]=sum(m[,i]^c(1:length(m[1,])))
}
m=as.vector(m[,rev(order(b))[1]])
Pf=c() # the winner set is transposed to prime form
Pf[1]=0
for(i in 1:(length(succ_i_arr)-1))
{
Pf[1+i]=Pf[i]+m[i]
}
}
return(Pf)
}
#******************#
Atte Tenkanen
University of Turku, Finland
More information about the R-help
mailing list