R 如何创建一个新变量,该变量的值取决于另一个包含特定单词的变量?
我有一个关于一系列文章的数据集:R 如何创建一个新变量,该变量的值取决于另一个包含特定单词的变量?,r,R,我有一个关于一系列文章的数据集: ID number, Header, Rubric, Article Text, Date. 我想根据内容对文章进行排序,即我想使用“if”语句创建一个新变量: “如果变量‘Article Text’包含字符串‘Second World War’”,则“‘New variable’=1和” “如果“变量‘Article Text’包含单词‘Syrian’”,则“‘新变量’=2 此后,我想根据“new Variable”的值创建新的数据集 我希望能够尝试不
ID number, Header, Rubric, Article Text, Date.
我想根据内容对文章进行排序,即我想使用“if”语句创建一个新变量:
- “如果变量‘Article Text’包含字符串‘Second World War’”,则“‘New variable’=1和”
- “如果“变量‘Article Text’包含单词‘Syrian’”,则“‘新变量’=2
- 此后,我想根据“new Variable”的值创建新的数据集李>
- 一个字
- 围绕同一主题的几个单词(全部在文本中)
- 围绕同一主题的几个单词(文本中的一个或多个)
- 字串
提前感谢一个最简单的例子是:
# An example data.frame containing some combinations of letters:
data <- data.frame(a=paste0(LETTERS[1:3],LETTERS[3:5]))
# Replace this with the strings you want to search for:
strings <- c("A", "C")
# And this with the names for the new columns:
names(strings) <- c("colA", "colB")
# Search for the strings and create new columns, replace $a according to your column-names:
data <- cbind(data, data.frame(lapply(strings, grepl, data$a)))
#包含一些字母组合的示例data.frame:
对于搜索的每个字符串,我首先使用多个逻辑变量返回数据,因为项目可能包含多个字符串。第二,数据集的形式是什么?您是从文件或数据库中读取它,还是将其作为data.frame或list…非常感谢。你肯定是对的,文章可能包含更多的字符串。我将数据作为R中的数据帧。