I want to split based on :: but it doesnt work for the entire vector
我想基于::但它不适用于整个矢量
str<- c("bob::jhh","jjj::dfff")
data<- as.data.frame(x)
data
data$new.col <-strsplit(as.character(b[,1]),"::")[[1]][2]
data
output
产量
data new.col
1 bob::jhh jhh
2 jjj::dfff jhh #<<--this should be dfff not jhhh.
any idea how to make it return jhh dfff instead of jhh jhh?
任何想法如何让它返回jhh dfff而不是jhh jhh?
2 个解决方案
#1
1
sapply can be used here:
sapply可以在这里使用:
str<- c("bob::jhh","jjj::dfff")
ss = strsplit(str, split="::")
sapply(ss, function(x) x[2])
[1] "jhh" "dfff"
It can be put in the dataframe:
它可以放在数据帧中:
nn = sapply(ss, function(x) x[2])
dataf$new = nn
dataf
str new
1 bob::jhh jhh
2 jjj::dfff dfff
#2
0
strsplit
returns a list, so you need to process that list. For example
strsplit返回一个列表,因此您需要处理该列表。例如
str <- c("bob::jhh","jjj::dfff", "another::string", "foo::bar")
dat <- do.call(rbind, strsplit(str, split="::"))
This creates a matrix, first column is everything on left of ::
and second column everything on the right of ::
这会创建一个矩阵,第一列是::左边的所有内容,第二列是右边的所有内容::
#1
1
sapply can be used here:
sapply可以在这里使用:
str<- c("bob::jhh","jjj::dfff")
ss = strsplit(str, split="::")
sapply(ss, function(x) x[2])
[1] "jhh" "dfff"
It can be put in the dataframe:
它可以放在数据帧中:
nn = sapply(ss, function(x) x[2])
dataf$new = nn
dataf
str new
1 bob::jhh jhh
2 jjj::dfff dfff
#2
0
strsplit
returns a list, so you need to process that list. For example
strsplit返回一个列表,因此您需要处理该列表。例如
str <- c("bob::jhh","jjj::dfff", "another::string", "foo::bar")
dat <- do.call(rbind, strsplit(str, split="::"))
This creates a matrix, first column is everything on left of ::
and second column everything on the right of ::
这会创建一个矩阵,第一列是::左边的所有内容,第二列是右边的所有内容::