Given a dataframe, I would like to use strsplit
on one of my columns, and return the first element of the vector. Here is the example:
testdf<- data.frame(col1= c('string1.string2', 'string3.string4'),
col2= c('somevalue', 'someothervalue'),
stringsAsFactors = FALSE)
I want to generate a new column such as
testdf$col3 <- c('string1', 'string3')
I tried the following:
testdf$col3<- strsplit(testdf$col1, split = '\\.')[[1]])[1]
which, of course, doesn't work. It returns just the first element of the output ('string1') and writes it for the whole column. One solution would be to write a custom function:
customfx<- function(ind_cell){
my_out<- strsplit(ind_cell, split = '\\.')[[1]][1]
return(my_out)}
Then use it with sapply
. I was wondering if there is an alternative to this. The talking stick is yours :)