speeding up "pick up first string from unlist" in R
I am trying to capture the first string from a list using an explicit loop, as shown in the following code:
for (loop.temp in (1:nrow(temp)))
{temp[loop.temp,"drug_name_mod"]开发者_StackOverflow中文版 <- unlist(strsplit(temp[loop.temp,"drug_name"]," "))[1]
print(paste(loop.temp,nrow(temp),sep="/"))
flush.console()
}
But I think it is not very efficient, anyway of improving it? Thanks!
First strsplit the strings, this gives you a list of string vectors, then lapply across that to get only the first element, and unlist that:
temp$drug_name_mod <- unlist(lapply(strsplit(temp$drug_name, " "), function(x) x[1]))
sapply makes it slightly simpler:
temp$drug_name_mod <- sapply(strsplit(temp$drug_name, " "), function(x) x[1])
And you can use "[" directly with 1 as its argument rather than an anonymous function:
temp$drug_name_mod <- sapply(strsplit(temp$drug_name, " "), "[", 1)
精彩评论