apply strsplit rowwise

徘徊边缘 提交于 2019-11-29 21:54:00

This should do the trick

R> sapply(strsplit(as.character(h$tes), "\\."), "[[", 2)
[1] "abc" "di"  "lik"

With the stringr package it's even easier:

library(stringr)
str_split_fixed(h$tes, fixed("."), 2)[, 2]

This is the same as rcs' answer, but may be easier to understand:

> sapply(strsplit(as.character(h$tes), "\\."), function(x) x[[2]])
[1] "abc" "di"  "lik"
Marek

This question appears several time on StackOverflow.

In exact form as yours:

Some similar question in this topic:

And if you care about speed then you should consider tip from John answer about fixed parameter to strsplit.

Alternatively, you can save yourself the work of pulling out the 2nd element if you add both columns at the same time:

tes <- c("1.abc","2.di","3.lik")
dat <- c(5,3,2)
h <- data.frame(tes, dat, stringsAsFactors=FALSE)
values <- unlist(strsplit(h$tes, ".", fixed=TRUE))
h <- cbind(h, matrix(values, byrow=TRUE, ncol=2,
                     dimnames=list(NULL, c("num", "prim"))))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!