[R] (no subject)

arun smartpink111 at yahoo.com
Fri Nov 1 22:38:08 CET 2013



Hi,

Check whether this works:


vec1 <- c( 'eric', 'JOHN', 'eric', 'JOHN', 'steve', 'scott', 'steve', 'scott', 'JOHN', 'eric')
vec2 <- c( 'eric', 'JOHN', 'eric', 'eric', 'JOHN', 'JOHN', 'steve', 'steve', 'scott', 'scott')
vec3 <- c( 'eric', 'eric', 'JOHN', 'eric', 'JOHN', 'JOHN', 'steve', 'steve', 'scott', 'scott')

vec4 <- c( 'eric', 'eric', 'JOHN', 'eric', 'JOHN', 'steve', 'steve', 'scott', 'scott','JOHN')
vec5 <- c('JOHN', 'JOHN', 'eric', 'eric', 'JOHN', 'eric', 'steve', 'steve', 'scott', 'scott')
vec6 <- c( 'eric', 'eric',  'eric', 'JOHN','JOHN', 'JOHN', 'steve', 'steve','scott', 'scott')
vec7 <- c( 'eric', 'eric',  'eric', 'JOHN','JOHN', 'JOHN', 'steve', 'scott', 'scott', 'steve')
fun1 <- function(vec) {
 sum(unlist(sapply(unique(vec),function(x) {x1 <- diff(which(vec %in% x)); ifelse(x1==1, 1, -x1)}),use.names=FALSE))
 }


A.K.






I took a steve and put it at the end of the vector.  score should be less as the steves are farther apart.

> vec3 <- c( 'eric', 'eric',  'eric', 'JOHN','JOHN', 'JOHN', 'steve', 'steve','scott', 'scott')
> sum(diff(vec3[-1]!=vec3[-length(vec3)])) +  sum(vec3[-1]== vec3[-length(vec3)])
[1] 6

> vec4 <- c( 'eric', 'eric',  'eric', 'JOHN','JOHN', 'JOHN', 'steve', 'scott', 'scott', 'steve')
> sum(diff(vec4[-1]!=vec4[-length(vec4)])) +  sum(vec4[-1]== vec4[-length(vec4)])
[1] 6

S



More information about the R-help mailing list