r - R中的目标变量重新编码

标签 r variables data-manipulation

我正在尝试进行一些文本处理,并且需要重新编码句子中的单词,以便在新变量中以特定方式识别目标单词。例如,给定一个看起来像这样的数据框......

subj <- c("1", "1", "1", "2", "2", "2", "2", "2")
condition <- c("A", "A", "A", "B", "B", "B", "B", "B")
sentence <- c("1", "1", "1", "2", "2", "2", "2", "2")
word <- c("I", "like", "dogs.", "We", "don't", "like", "this", "song.")
d <- data.frame(subj,condition, sentence, word)

 subj condition sentence  word
 1         A        1     I
 1         A        1     like
 1         A        1     dogs.
 2         B        2     We
 2         B        2     don't
 2         B        2     like
 2         B        2     this
 2         B        2     song.

我需要创建一个新列,其中目标单词的每个实例(在本例中,当 d$word="like"时)都标记为 0,并且句子块中“like”之前的所有单词和“之后的所有单词”都递减喜欢”增量。每个主题有多个句子,句子因条件而异,因此循环需要考虑每个主题、每个句子的目标词实例。最终结果应该是这样的。
 subj condition sentence  word   position
 1         A        1     I        -1
 1         A        1     like      0
 1         A        1     dogs.     1
 2         B        2     We       -2
 2         B        2     don't    -1
 2         B        2     like      0
 2         B        2     this      1
 2         B        2     song.     2

对不起,如果问题措辞不当,我希望它是有道理的!请注意,每个句子中的目标不在同一个位置(相对于句子的开头)。我对 R 很陌生,可以弄清楚如何递增或递减,但不能在每个句子块中同时做这两件事。有关解决此问题的最佳方法的任何建议?非常感谢!

最佳答案

您可以添加一个索引,然后您可以将其用于相对位置。
使用 data.table通过 sentence 将其分解好简单

library(data.table)
DT <- data.table(indx=1:nrow(d), d, key="indx")

DT[, position:=(indx - indx[word=="like"]), by=sentence]

# Results
DT
#    indx subj condition sentence  word position
# 1:    1    1         A        1     I       -1
# 2:    2    1         A        1  like        0
# 3:    3    1         A        1 dogs.        1
# 4:    4    2         B        2    We       -2
# 5:    5    2         B        2 don't       -1
# 6:    6    2         B        2  like        0
# 7:    7    2         B        2  this        1
# 8:    8    2         B        2 song.        2

日期:

如果您有语法错误的句子,您可能需要使用 grepl而不是 ==
DT[, position:=(indx - indx[grepl("like", word)]), by=sentence]

关于r - R中的目标变量重新编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15193441/

相关文章:

r - 在 r 笔记本中添加目录

r - 在 R 中的数据帧中将负值转换为零

r - 是否可以在没有 %% 的情况下定义运算符?

python - 使用 python 设置批处理变量

r - 用 NA 填充两个矩阵的缺失数据

r - 根据两列R分配ID

r - 在 R 包中动态创建函数

c - 什么是 C 中的标量变量?

regex - 基于 Django 类的通用 View URL 变量传递

在 R 中重构数据