CarLinneo
CarLinneo

Reputation: 47

is Ifelse... the right function to use here?

I am trying to use ifelse to populate a new column in a data frame. I want to extract the last digits of a character string in a column if this is longer than 3. if the charachter string is shorter I just want it to give -1...

I already figured out how to extract the last characters of the string if the string is longer than 3 characters.


x<- c("ABCD1", "ABCD2", "ABCD3", "ABCD4", "BC5", "BC6", "BC7")
y<-NULL
dat<-cbind(x,y)

ifelse (nchar(x>3), y=substr(x, 5,5), y=-1)

dat<-cbind(x,y)
view(dat)

when I run this, I get the next error

  Error in ifelse(nchar(x > 3), y = substr(x, 4, 5), y = substr(x, 3)) : 
   formal argument "yes" matched by multiple actual arguments`

What I want is that vector "y" gets the numbers 1,2,3,4,-1,-1,-1 so I can bind both columns latter. If you have a better way of doing this I would appreciate it.

Upvotes: 1

Views: 122

Answers (2)

Shree
Shree

Reputation: 11150

I am guessing you need a dataframe. Here's what you probably need -

x <- c("ABCD1", "ABCD2", "ABCD3", "ABCD4", "BC5", "BC6", "BC7")
dat <- data.frame(x, stringsAsFactors = F)

dat$y <- ifelse(nchar(dat$x) > 3, as.numeric(substr(dat$x, 5,5)), -1)

      x  y
1 ABCD1  1
2 ABCD2  2
3 ABCD3  3
4 ABCD4  4
5   BC5 -1
6   BC6 -1
7   BC7 -1

Upvotes: 0

Brigadeiro
Brigadeiro

Reputation: 2945

You're almost there! This will work as long as the strings with length > 3 are 4 characters long.

ifelse(nchar(x) > 3, substr(x, 5, 5), -1)

If your strings might be longer than 4 characters:

ifelse(nchar(x) > 3, sub(".*([0-9]).*", "\\1", x), -1)

Upvotes: 1

Related Questions