使用R

时间:2016-07-14 20:23:02

标签: r math statistics

想象一下以下的序列:

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

由于相似性,我想按此顺序对序列进行排序:

0000
0001
0010
0100
1000
0011
...

第2,3,4,5行与第1行具有相同的相似性,因为它们仅相差一位。因此2,3,4,5行的顺序也可以是3,2,5,4。

接下来是第6行,因为它与第1行相差2位。

这可以用R吗?

完成

3 个答案:

答案 0 :(得分:7)

x <- c("0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", 
       "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111")

1)使用this中的digitsum函数回答:

digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
x[order(sapply(as.numeric(x), digitsum))]
#  [1] "0000" "0001" "0010" "0100" "1000" "0011" "0101" "0110" "1001" "1010" "1100"
# [12] "0111" "1011" "1101" "1110" "1111"

2)使用正则表达式:

x[order(gsub(0, "", x))]
#  [1] "0000" "0001" "0010" "0100" "1000" "0011" "0101" "0110" "1001" "1010" "1100"
# [12] "0111" "1011" "1101" "1110" "1111"

答案 1 :(得分:3)

由于我们讨论的是字符串距离,您可能希望使用stringdist包中的stringdist函数来执行此操作:

library(stringdist)
x <- c("0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", 
       "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111")

#stringdistmatrix(x) will calculate the pairwise distances from the lowest value
#0000 in this case
distances <- stringdistmatrix(x, '0000')

#use the distances to order the vector
x[order(distances)]
#[1] "0000" "0001" "0010" "0100" "1000" "0011" "0101" "0110" 
#    "1001" "1010" "1100" "0111" "1011" "1101" "1110" "1111"

或者一气呵成:

x[order(stringdist(x, '0000'))]

答案 2 :(得分:1)

嗯,这就是我的尝试。试一试,看看它是否符合您的需求。它取决于stringr

library('stringr')
# Creates a small test data frame to mimic the data you have.
df <- data.frame(numbers = c('0000', '0001', '0010', '0011', '0100', '0101', '0111', '1000'), stringsAsFactors = FALSE)
df$count <- str_count(df$numbers, '1') # Counts instances of 1 occurring in each string
df[with(df, order(count)), ] # Orders data frame by number of counts.

  numbers count
1    0000     0
2    0001     1
3    0010     1
5    0100     1
8    1000     1
4    0011     2
6    0101     2
7    0111     3