R: read and convert to number

I have a dataframe with the following format.

AB xxx 100;2;30;5 yyy 30;5 zzz 35 

How to count the number of numbers in column B in the second column and convert to count as follows:

 AB xxx 4 yyy 2 zzz 1 

Thanks.

+4
source share
2 answers

Assuming your data is in data.frame named Data , a combination of strsplit and sapply does a short job.

 Data$C <- sapply(strsplit(Data$B, ";"), length) 

strsplit vectorized, so it splits each element of the Data$B column into ";" and returns a list of vectors. The list has one element for each row in Data , and each element of the list contains a vector (for example, "100;2;30;5" converted to c("100","2","30","5") ). The sapply call returns the length of each vector in the list.

+8
source

This is the trick:

 dfr$B<-nchar(as.character(dfr$B))-nchar(gsub(";","",dfr$B))+1 

Edit: I think this should be a little faster:

 dfr$B<-nchar(as.character(dfr$B))-nchar(gsub(";","",dfr$B, fixed=TRUE))+1 
0
source

All Articles