简体   繁体   中英

R: Surrogate for selecting rownames on a tibble column

The question is how to use a column on a tibble to select the whole row. The code below shows what I normally do using basic R functions to index rows I want to eliminate form the data frame dataMet. I was wondering if I can use tidyverse functions on a tibble to get the same results. Thanks!

outL <- c("S11", "S156", "S302")
index <- match(outL, rownames(dataMet))

# Print Outliers
outL
dataMet[index,]

# Remove Outliers
dataMet <- dataMet[-index,]

EDIT: to clarify, I want to conduct this operation without using rownames. Instead, I want to subset the data according to matches between a vector and a column.

More options

library(dplyr)


mydata <- data.frame(col1 = letters[1:10],
           col2 = 1:10)

slice(mydata, c(1, 3, 5))
#>   col1 col2
#> 1    a    1
#> 2    c    3
#> 3    e    5

slice(mydata, c(-1, -3, -5))
#>   col1 col2
#> 1    b    2
#> 2    d    4
#> 3    f    6
#> 4    g    7
#> 5    h    8
#> 6    i    9
#> 7    j   10

mydata$rownumber <- 1:nrow(mydata)

mydata$crownumber <- as.character(1:nrow(mydata))
str(mydata)

#> 'data.frame':    10 obs. of  4 variables:
#>  $ col1      : chr  "a" "b" "c" "d" ...
#>  $ col2      : int  1 2 3 4 5 6 7 8 9 10
#>  $ rownumber : int  1 2 3 4 5 6 7 8 9 10
#>  $ crownumber: chr  "1" "2" "3" "4" ...

myvector <- c(1, 2, 5)
mycvector <- c("6", "4", "8")

mydata %>% filter(col2 %in% myvector)
#>   col1 col2 rownumber crownumber
#> 1    a    1         1          1
#> 2    b    2         2          2
#> 3    e    5         5          5

mydata %>% filter(col2 %in% mycvector)
#>   col1 col2 rownumber crownumber
#> 1    d    4         4          4
#> 2    f    6         6          6
#> 3    h    8         8          8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM