Jim
Jim

Reputation: 578

A simple, quick method to extract a single value in a dataframe based on an adjacent column contents

I have the following .txt file, read in as such.

abc <- "           V1                   V2
1               Version                        2.1
2               StationName               AngryFly
3               BeginTime      2019-14-07.21:21:00
4               EndTime        2019-14-07.22:21:00
5               IgnoreNo                     50000
6               PumpedVolume         notCalculated
7               NoSamples                      500
8               NoPickable                  107515
9               Ignored                          0"

# Plus a few more excluded rows


df <- read.table(text = abc, header = TRUE)

I have had a good look around and have managed an totally overcomplicated solution but there must be a better way.

I am looking to extract as.numeric the NoPickable.

I want the following:

> print(NoPickable)
[1] 107515

Many thanks

Upvotes: 0

Views: 32

Answers (1)

Giora Simchoni
Giora Simchoni

Reputation: 3689

I'm guessing your problem is that R by default reads the second column V2 as factor.

Do:

df <- read.table(text = abc, header = TRUE, stringsAsFactors = FALSE)

And then:

as.numeric(df$V2[df$V1=="NoPickable"])

or in tidyverse:

df %>% filter(V1 == "NoPickable") %>% pull(V2) %>% as.numeric()

Upvotes: 1

Related Questions