Frage

I have some words:

shapes<- c("Square", "Triangle","Octagon","Hexagon")

I want to arrange them in pairs:

shapescount<-combn(shapes, 2)

shapescount

[,1]       [,2]      [,3]      [,4]       [,5]       [,6]     
[1,] "Square"   "Square"  "Square"  "Triangle" "Triangle" "Octagon"
[2,] "Triangle" "Octagon" "Hexagon" "Octagon"  "Hexagon"  "Hexagon"

I want to count each of the groupings of the letters in the pairs, for instance first pair is "6" for "Square" and "8" for "Triangle" giving me "14" for the first pair, and so on.

War es hilfreich?

Lösung 2

One way:

colSums(combn(shapes, 2, FUN=nchar))
# [1] 14 13 13 15 15 14

Benchmarks:

shapes <- rep(c("Square", "Triangle","Octagon","Hexagon"), 50)
matthew <- function() colSums(combn(shapes, 2, FUN=nchar))
ananda <- function() combn(shapes, 2, FUN=function(x) sum(nchar(x)))
tstenner <- function() {
    shapelengths <- nchar(shapes)
    colSums(combn(shapelengths, 2))
}
microbenchmark(matthew(), ananda(), tstenner())
# Unit: milliseconds
#        expr   min    lq median    uq    max neval
#   matthew() 53.27 55.84  56.37 57.04  98.83   100
#    ananda() 74.74 78.42  79.88 80.60 123.29   100
#  tstenner() 29.27 31.03  31.52 33.44  76.01   100

Andere Tipps

Use apply and nchar:

> apply(shapescount, 2, function(x) sum(nchar(x)))
[1] 14 13 13 15 15 14

Since combn also has a FUN argument, you can do it all in one go:

> combn(shapes, 2, FUN=function(x) sum(nchar(x)))
[1] 14 13 13 15 15 14

You're likely looking for nchar.

To make things faster, don't compute all permutations of strings but of string lengths:

shapes<- c("Square", "Triangle","Octagon","Hexagon")
shapelengths <- nchar(shapes)
colSums(combn(shapelengths, 2))

If you're looking for one expression, simply inline the call to nchar():

colSums(combn(nchar(shapes), 2))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top