[英]Grabs rows where second column is equal to value
我有一個看起來像這樣的數據集:
print(animals_in_zoo)
// I only know the name of the first column, the second one is dynamic/based on a previously calculated variable
animals | dynamic_column_name
// What the data looks like
elefant x
turtle
monkey
giraffe x
swan
tiger x
我想要的是收集第二列的值等於“x”的行。
我想做的是這樣的:
SELECT * 來自 col2 == "x" 的數據;
之后,我只想抓取第一列並創建一個字符串 object,如“elefant giraffe tiger”,但這是比較容易的部分。
我們可以將filter
與grepl
一起使用,它在字符串中搜索模式“x”:
# the data frame
df <- read.table(header = TRUE, text =
'my_col
"elefant x"
turtle
monkey
"giraffe x"
swan
"tiger x"'
)
library(dplyr)
df %>%
filter(grepl('x', my_col))
my_col
1 elefant x
2 giraffe x
3 tiger x
使用[
:第一個參數指的是行。 您想要第二列為"x"
的行。 第二個參數是你最后需要的列,你想要名為"animals"
的列:
dat[dat[2] == "x", "animals"]
#[1] "elefant" "giraffe" "tiger"
數據
dat <- structure(list(animals = c("elefant", "turtle", "monkey", "giraffe",
"swan", "tiger"), V2 = c("x", "", "", "x", "", "x")), row.names = c(NA,
-6L), class = "data.frame")
# animals V2
# 1 elefant x
# 2 turtle
# 3 monkey
# 4 giraffe x
# 5 swan
# 6 tiger x
您可以通過其索引引用該列並使用它來獲取您想要的動物:
df1 <- structure(list(animal = c("elefant", "turtle", "monkey", "giraffe",
"swan", "tiger"), dynamic_column = c("x", NA, NA, "x", NA, "x"
)), row.names = c(NA, -6L), class = "data.frame")
df1[, 1][df1[, 2] == "x" & !is.na(df1[, 2])]
#> [1] "elefant" "giraffe" "tiger"
我猜你有一個 dataframe?
如果是這樣,像df[df$col2 == 'x',]
這樣的東西應該可以工作。
使用base
函數,您可以這樣做:
# Option 1
your_dataframe[your_dataframe$col2 == "x", ]
# Option 2
your_dataframe[your_dataframe[,2] == "x", ]
使用dplyr
函數,您可以這樣做:
library(dplyr)
your_dataframe %>%
filter(col2 == "x")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.