【问题标题】:Grabs rows where second column is equal to value抓取第二列等于值的行
【发布时间】:2022-12-18 09:30:33
【问题描述】:

我有一个看起来像这样的数据集:

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 * from data where col2 == "x";

之后,我只想抓取第一列并创建一个字符串对象,如“elefant giraffe tiger”,但这是比较容易的部分。

【问题讨论】:

    标签: r dataframe modeling


    【解决方案1】:

    我们可以使用 filtergrepl 来搜索字符串中的模式 '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
    

    【讨论】:

      【解决方案2】:

      我猜你有一个数据框?

      如果是这样,df[df$col2 == 'x',] 之类的东西应该可以工作。

      【讨论】:

      • 试过了,好像不行
      • 我想问题是你的原始文件是如何格式化的(如果你有一个文件)以及你是如何将数据加载到 r 中的。
      【解决方案3】:

      您可以通过其索引引用该列并使用它来获取您想要的动物:

      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")
      
      dplyr::filter(df1, df1[, 2] == "x")$animal
      #> [1] "elefant" "giraffe" "tiger"
      

      【讨论】:

        【解决方案4】:

        使用 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")
        

        【讨论】:

          【解决方案5】:

          使用[:第一个参数指的是行。您需要第二列为"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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-09-28
            • 1970-01-01
            • 1970-01-01
            • 2017-03-11
            • 2022-10-06
            • 2022-01-17
            • 2018-09-20
            • 1970-01-01
            相关资源
            最近更新 更多