用R对二进制序列进行排序
想象一下下面的序列:用R对二进制序列进行排序,r,math,statistics,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来完成吗?好吧,我试过了。试一试,看看
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来完成吗?好吧,我试过了。试一试,看看是否适合你的需要。它确实取决于
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
library('stringr')
#创建一个小的测试数据框来模拟您拥有的数据。
dfLet
2) 使用正则表达式:
x[order(gsub(0, "", x))]
# [1] "0000" "0001" "0010" "0100" "1000" "0011" "0101" "0110" "1001" "1010" "1100"
# [12] "0111" "1011" "1101" "1110" "1111"
由于我们讨论的是字符串距离,因此您可能希望使用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"
这仅在第一个条目为0000
时有效。OP可能需要一个更通用的解决方案来代替digitsum函数,你能做到这一点吗:x[顺序(sapply(strsplit(x,”),函数(x)sum(x==1))]
@eipi10,当然,但正则表达式的解决方案可能比任何涉及数字求和的解决方案都要简洁。我同意。但在R中找出所有第二好的做事方法确实很有趣。
x[order(gsub(0, "", x))]
# [1] "0000" "0001" "0010" "0100" "1000" "0011" "0101" "0110" "1001" "1010" "1100"
# [12] "0111" "1011" "1101" "1110" "1111"
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'))]