On Thu, Dec 1, 2011 at 10:32 AM, Douglas Esneault
douglas.esnea...@mecglobal.com wrote:
I am new to R but am experienced SAS user and I was hoping to get some help
on counting the occurrences of a character within a string at a row level.
My dataframe, x, is structured as below:
Col1
I am new to R but am experienced SAS user and I was hoping to get some help on
counting the occurrences of a character within a string at a row level.
My dataframe, x, is structured as below:
Col1
abc/def
ghi/jkl/mno
I found this code on the board but it counts all occurrences of / in the
## It's not a data frame -- it's just a vector.
x
[1] abc/def ghi/jkl/mno
gsub([^/],,x)
[1] / //
nchar(gsub([^/],,x))
[1] 1 2
?gsub
?nchar
-- Bert
On Thu, Dec 1, 2011 at 8:32 AM, Douglas Esneault
douglas.esnea...@mecglobal.com wrote:
I am new to R but am experienced SAS user and I
I used within and vapply:
x - data.frame(Col1 = c(abc/def, ghi/jkl/mno), stringsAsFactors = FALSE)
count.slashes - function(string)sum(unlist(strsplit(string, NULL)) ==
/)within(x, Col2 - vapply(Col1, count.slashes, 1))
Col1 Col21 abc/def 12 ghi/jkl/mno 2
On Thu, Dec 1, 2011
Resending my code, not sure why the linebreaks got eaten:
x - data.frame(Col1 = c(abc/def, ghi/jkl/mno), stringsAsFactors = FALSE)
count.slashes - function(string)sum(unlist(strsplit(string, NULL)) == /)
within(x, Col2 - vapply(Col1, count.slashes, 1))
Col1 Col2
1 abc/def1
2
strsplit is certainly an alternative, but your approach is
unnecessarily complicated and inefficient. Do this, instead:
sapply(strsplit(x,/),length)-1
Cheers,
Bert
On Thu, Dec 1, 2011 at 7:44 PM, Florent D. flo...@gmail.com wrote:
Resending my code, not sure why the linebreaks got eaten:
x -
Inefficient, maybe, but what you suggest does not work if a string
starts or ends with a slash.
On Thu, Dec 1, 2011 at 11:11 PM, Bert Gunter gunter.ber...@gene.com wrote:
strsplit is certainly an alternative, but your approach is
unnecessarily complicated and inefficient. Do this, instead:
On Dec 1, 2011, at 11:11 PM, Bert Gunter wrote:
strsplit is certainly an alternative, but your approach is
unnecessarily complicated and inefficient. Do this, instead:
sapply(strsplit(x,/),length)-1
Definitely more compact that the regex alternates I came up with, but
one of these still
8 matches
Mail list logo