S31
S31

Reputation: 934

Extracting a value based on multiple conditions in R

Quick question - I have a dataframe (severity) that looks like,

                    industryType  relfreq   relsev
 1              Consumer Products 2.032520 0.419048
 2                 Biotech/Pharma 0.650407 3.771429
 3        Industrial/Construction 1.327913 0.609524
 4  Computer Hardware/Electronics 1.571816 2.019048
 5                Medical Devices 1.463415 3.028571
 6                       Software 0.758808 1.314286
 7     Business/Consumer Services 0.623306 0.723810
 8             Telecommunications 0.650407 4.247619

if I wanted to pull the relfreq of Medical Devices (row 5) - how could I subset just that value?

I was thinking about just indexing and doing severity$relfreq[[5]], but I'd be using this line in a bigger function where the user would specify the industry i.e.

example <- function(industrytype) {
   weight <- relfreq of industrytype parameter

   thing2 <- thing1*weight
   return(thing2)
 }

So if I do subset by an index, is there a way R would know which index corresponds to the industry type specified in the function parameter? Or is it easier/a way to just subset the relfreq column by the industry name?

Upvotes: 1

Views: 1300

Answers (2)

stuski
stuski

Reputation: 199

You would require to first select the row of interest and then keep the 2 column you requested (industryType and relfreq). There is a great package that allows you to do this intuitively with tidyverse library(tidyverse)

data_want <- severity %>% subset(industryType =="Medical Devices") %>% select(industryType, relfreq)

Here you read from left to right with the %>% serving as passing the result to the next step as if nesting.

Upvotes: 1

piotr
piotr

Reputation: 152

I think that selecting whole row is better, then choose column which you would like to see.

frame <- severity[severity$industryType == 'Medical Devices',]
frame$relfreq

Upvotes: 0

Related Questions