Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to R dataframe that is length of string in another column

Tags:

dataframe

r

This should be EASY but I can't figure it out and search didn't help. I'd like to add a column to a dataframe that is just the length of the strings in another column.

So say I have a data frame of names like such:

   Name    Last
1  John     Doe
2 Edgar     Poe
3  Walt Whitman
4  Jane  Austen

I'd like to append a new column with the string length of, say, the last name, so it would look like:

   Name    Last  Length
1  John     Doe  3
2 Edgar     Poe  3
3  Walt Whitman  7
4  Jane  Austen  6

Thanks

like image 678
Turbo Avatar asked Oct 18 '22 05:10

Turbo


1 Answers

We can use str_count from stringr

library(stringr)
df1$Length <- str_count(df1$Last)
df1$Length
[1] 3 3 7 6
like image 121
akrun Avatar answered Oct 21 '22 05:10

akrun