例如,我創建了這樣的資料
df<- structure(list(Names = c("AA", "ab", "CC", "AVY"), Column1 = c(0L,
0L, 0L, 1L), Column2 = c(0L, 0L, 0L, 0L), Column3 = c(0L, 0L,
0L, 1L)), class = "data.frame", row.names = c(NA, -4L))
我想子集并保留那些包含我的字串的行,如果我想找到位置,可以說其中的 3 個,我可以使用以下內容找到 CC 的位置
which(df=="CC", arr.ind=TRUE)
或者如果我想找到其中兩個 CC 和 ab ,我可以
which(df==c("CC","ab"), arr.ind=TRUE)
但我想要的是將它放在一個新的資料框中,如下所示
Name Column1 Column2 Column3
ab 0 0 0
CC 0 0 0
我當時根據其他人的解決方案找到了一個字串,但如果我有多個字串,我不知道該怎么做
df[sapply(df, function(x) grepl("CC",x)),]
uj5u.com熱心網友回復:
使用%in%or subset,不需要whichor sapply。
df[df$Names %in% c("CC","ab"), ]
# Names Column1 Column2 Column3
# 2 ab 0 0 0
# 3 CC 0 0 0
subset(df, Names %in% c("CC","ab"))
# Names Column1 Column2 Column3
# 2 ab 0 0 0
# 3 CC 0 0 0
%in%是 的近親match。
df$Names %in% c("CC","ab")
# [1] FALSE TRUE TRUE FALSE
基本上是
!is.na(match(df$Names, c("CC","ab")))
# [1] FALSE TRUE TRUE FALSE
uj5u.com熱心網友回復:
您是否正在尋找這種解決方案:
隨著str_detect我們可以與模式定義字串過濾器|(或)運算子:
library(dplyr)
libray(stringr)
df %>%
filter(str_detect(Names, 'CC|ab'))
Names Column1 Column2 Column3
1 ab 0 0 0
2 CC 0 0 0
uj5u.com熱心網友回復:
或者如果你提前知道你想要的名字......
library(dplyr)
my_names=c("ab","CC")
df_subset<-df %>%
filter(Names %in% my_names)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393438.html
標籤:r
下一篇:如何洗掉具有特定字串的所有行?
