tags:

views:

88

answers:

4

How do you get the length of a variable. I am trying to get the last character of factor but the width/length of the contents is variable.

I was trying to do something like this:

newvariable <- substr(oldvariable, length(oldvariable) -1, length(oldvariable))

A: 

What language is this?

Try:

right(oldvariable, 1)

Or

newvariable <- substr(oldvariable, length(oldvariable) -1)

Tom Gullen
R is a functional statistical programming language based off the S language.
Brandon
+3  A: 

I'm not 100% sure I got the question... but I guess what you need is nchar

len <- nchar(variable)
nico
A: 

I'm also not 100% sure what you want with this question either. I'm guessing you have dataset with a factor column and you want to truncate the factor levels to just the last letter of each level.

#gather the current levels, we'll call it 'lev'
lev<-levels(oldvariable)

#use substr and char on 'lev' to get the last letter of each level
newvariable<-substr(lev, nchar(lev), nchar(lev))

#reset the levels on the 'oldvariable' to the last letter using the results in 'newvariable'
levels(oldvariable)<-newvariable
Brian
+2  A: 
newvariable <- factor(substr(as.character(oldvariable),nchar(as.character(oldvariable)),nchar(as.character(oldvariable))))

Another one:

k <- levels(oldvariable)[oldvariable]
newvariable <- factor(substr(k,nchar(k),nchar(k)))
gd047
The first response worked great.
Brandon