Lin Ma
Lin Ma

Reputation: 10139

undefined columns error in R

Here is my simple R code. I want to only keep values which are smaller than 1.

Does anyone have any good ideas? Thanks.

df <- read.csv('~/Downloads/foo.tsv', sep='\t', header=F, stringsAsFactors=FALSE)
names(df) <- c('foo')
df$foo <- as.numeric(df$foo)

goodValue <- df[df$foo <= 1]

The last line has the following error:

Error in[.data.frame(df, df$foo <= 1) : undefined columns selected

Upvotes: 2

Views: 135

Answers (2)

akrun
akrun

Reputation: 886938

We can use data.table

library(data.table)
setDT(df)[foo <= 1]

Or with dplyr

library(dplyr)
df %>%
  filter(foo <= 1)

Upvotes: 1

Hack-R
Hack-R

Reputation: 23216

goodValue <- df[df$foo <= 1,] # if you want all columns
goodValue <- df$foo[df$foo <= 1] # if you only want foo (if you had multiple columns)

Upvotes: 1

Related Questions