【问题标题】:R - Delete unique rows in "neighborhood"R - 删除“邻居”中的唯一行
【发布时间】:2015-08-23 01:04:02
【问题描述】:

我输入了以下格式的数据

 stress word
 0      hello
 1      hello
 1      this
 1      is
 1      a
 1      normal
 0      normal
 1      test
 1      hello

我想得到输出

stress  word       stress_pos
 0      hello      2
 1      hello      2
 1      normal     1
 0      normal     1

该数据集是一个大列表,其中包含指示单词重音位置的单词 - 如果包含单词的第 k 行是第一列中的 1,则重音位于第 k ^ 个音节上。单词可能出现在列表中的多个位置,所以我想删除 3 行范围内的非重复项(每行查看上一行和下一行)。我只处理双音节词。这就是为什么我只关注直接邻居。

我不能使用duplicated()unique()(或者我不知道如何使用),因为它们会处理整个表格,而不仅仅是其中的一小部分。

第三栏表示单词中重音的位置,可以从第一栏推导出来。

有没有办法不使用循环?什么是解决这个问题的好方法?

【问题讨论】:

  • 老实说,我仍然无法弄清楚输出以及它是如何到达那里的。什么是stress_pos,如何总结?
  • 你是在说你好,而不是你好。所以在你好,压力在第二位。因此,stress_pos 下的任何地方都有一个 2 表示你好。第二个你好在stress下面有一个1,因为第二个音节重读
  • 那么为什么输出的第一行stress_pos中有2个呢?你是如何计算 2 的?
  • 第一行有一个2,因为hello在第二个位置有重音。出于同样的原因,第二行有一个 2。
  • 很好,但是根据你的原始数据,你是怎么知道你好在第二个位置有压力的?

标签: r duplicates unique vectorization


【解决方案1】:

首先,让我们考虑如何删除所有在距离 3 内不被另一个单词重复的单词。您可以通过以下方式确定每个单词是否与具有差异的单词d 匹配:

matches <- function(words, d) {
  words <- as.character(words)
  if (d < 0) {
    words == c(rep("", -d), head(words, d))
  } else {
    words == c(tail(words, -d), rep("", d))
  }
}

然后您可以通过以下方式获取数据的适当行:

(out <- dat[rowSums(sapply(c(-1, 1), function(d) matches(dat$word, d))) > 0,])
#   stress   word
# 1      0  hello
# 2      1  hello
# 6      1 normal
# 7      0 normal

剩下的就是确定重读的音节:

out$word <- as.character(out$word)
out$stress_pos <- ave(out$stress, out$word, FUN=function(x) min(which(x == 1)))
out
#   stress   word stress_pos
# 1      0  hello          2
# 2      1  hello          2
# 6      1 normal          1
# 7      0 normal          1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-09
    • 2014-12-17
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多