Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract last 2 chars from a column in a data.frame

I am new to R programming and have searched SO for many hours. I would appreciate your help.

I have a dataframe, with 3 columns (Date,Description, Debit)

      Date         Description   Debit
2014-01-01      "abcdef    VA"      15
2014-01-01     "ghijkl"    NY"      56

I am trying to extract the last 2 chars of the second (Description) column (i.e. the 2 letter state abbreviation). I am not very comfortable with apply-type functions.

I have tried using

 l <- lapply(a$Description, function(x) {substr(x, nchar(x)-2+1, nchar(x))})

but get the following error message

Error in nchar(x) : invalid multibyte string, element 1 

I have tried multiple other approaches, but with the same error.

I am quite sure that I am missing something very basic, so would appreciate your help

thanks

like image 863
MVigoda Avatar asked May 02 '16 23:05

MVigoda


1 Answers

library(stringr)
str_sub(a$Description,-2,-1)
like image 119
Sotos Avatar answered Sep 20 '22 14:09

Sotos