我在 R 中有一个包含一百多行字符的数据集。
我正在尝试删除所有以“.”开头和结尾的行。时期的性格。 我会先将这些行设置为空白,然后通过将它们写入 .csv 文件来删除它们。问题在第一部分,我如何先将它们设置为空白?
以下是我尝试过的 gsub 命令,但未对任何行执行任何操作。
#remove all periods followed by a space
data$text<- gsub('^([.][.])$', '', data$text)
data$text <- gsub('[.]*$',"",data$text) # with over a hundred rows
Value text
1 male occupied
2 male occupied
3 female occupied
4 . . . .
5 male occupied
6 . . .
7 female occupied
8 . .
我的预期输出:
Value text
1 male occupied
2 male occupied
3 female occupied
5 male occupied
7 female occupied
我如何在 R 中执行此操作? gsub 是正确的选择吗?
最佳答案
gsub
是从字符串中删除/替换子字符串的全局替换。根据 ?gsub
The two *sub functions differ only in that sub replaces only the first occurrence of a pattern whereas gsub replaces all occurrences.
这里的目的是找到向量中模式的位置并删除向量或列中的那些元素(从数据帧中删除行)。 grep
文档说
grep, grepl, regexpr, gregexpr and regexec search for matches to argument pattern within each element of a character vector: they differ in the format of and amount of detail in the results.
因此,我们得到数字索引(grep
)或逻辑向量(grepl
)输出并对 ddata 进行子集化
df1[!grepl("^\\.|\\.$", df1$text),]
在这里,我们匹配了一个.
(.
是任何字符的元字符——所以要得到字面意思,要么转义(\\
) 或将其放在方括号 ([.]
) 中或使用 fixed = TRUE
- 这里有 |
,所以我们不能在字符串的开头 (^
) 或结尾 ($
) 使用该选项)以使用 grepl
返回逻辑向量,取反(!
) 以便 TRUE -> FALSE 和 FALSE -> TRUE 并使用它来过滤行。
关于删除在 R 中开始和结束处包含句点的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044806/