开发者

speeding up "pick up first string from unlist" in R

开发者 https://www.devze.com 2023-02-01 07:34 出处:网络
I am trying to capture the first string from a list using an explicit loop, as shown in the following code:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号