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
data.frame(id = c(1,2,3), date1_count_character = c("13","9","17"), date2 = c("17","13","17"))
CodePudding user response:
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"))