Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any command to create new columns and include the characters?

Having a dataframe such as this:

df <- data.frame(id = c(1,2,3), date1 = c("2014-Dec 2018","2009-2010","Jan 2009-Aug 2010"), date2 = c("Feb 2016-Dec 2018","2014-Dec 2018","Oct 2013-Dec 2018"))

How is it possible to create a new one which will have in every column the number of characters, taking into consideration the missing values and insert in them 0

Example output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data.frame(id = c(1,2,3), date1_count_character = c("13","9","17"), date2 = c("17","13","17"))

>Solution :

What about something like this:

cbind(id = df[,1],as.data.frame(lapply(df[,-1], nchar)))

  id date1 date2
1  1    13    17
2  2     9    13
3  3    17    17

In case of NAs:

res <- cbind(id = df[,1],as.data.frame(lapply(df[,-1], nchar)))
res[is.na(res)] <- 0
  id date1 date2
1  1    13    17
2  2     9    13
3  3     0    17

With data with a NA:

df <- data.frame(id = c(1,2,3), date1 = c("2014-Dec 2018","2009-2010",NA), date2 = c("Feb 2016-Dec 2018","2014-Dec 2018","Oct 2013-Dec 2018"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading