gpt4 book ai didi

r - 当行包含相同字符时删除列

转载 作者:行者123 更新时间:2023-12-04 18:16:42 25 4
gpt4 key购买 nike

我有一个字符/数字组合矩阵,我需要删除那些列的两行中都出现相同字符的列。对于一个简化的例子:

> chars <- c("A1","A2","B1","B2")
> charsmat <- combn(chars, 2)
> charsmat
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "A1" "A1" "A1" "A2" "A2" "B1"
[2,] "A2" "B1" "B2" "B1" "B2" "B2"

当单列的两行包含相同的字符(在本例中为第 1 列和第 6 列)时,我需要删除该列。我觉得我有碎片:使用 gsub()str_extract()隔离字符,并测试行之间是否匹配,但我不知道如何制定它。提前感谢您提供的任何帮助。

最佳答案

首先,创建一个仅提取字母部分的新矩阵:

> (charsmat.alpha <- substr(charsmat, 0, 1))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "A" "A" "A" "A" "A" "B"
[2,] "A" "B" "B" "B" "B" "B"

然后,从 charsmat 中获取列的子集其中 charsmat.alpha 的两行不一样:

> charsmat[,(charsmat.alpha[1,] != charsmat.alpha[2,])]
[,1] [,2] [,3] [,4]
[1,] "A1" "A1" "A2" "A2"
[2,] "B1" "B2" "B1" "B2"

关于r - 当行包含相同字符时删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11529190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com