Erick
Erick

Reputation: 133

filtering data.frame character column in r

I have a variable term which includes loan term and has only two types: "36 months" and "60 months". I want to filter my dataset df and create two different subsets for these categories.

I have tried using the commands subset, filter,which etc but it didn't work.

codes that I have tried df1 –> df[which(df$term == "36 months"),], df1 –> filter(df, term == "36 months") df1–>df[df$term %in% c("36 months"), ] and other ways but always choices zero rows.

head(loan_data$term)

[1] " 36 months" " 60 months" " 36 months" " 36 months" " 60 months" " 36 months"

Any suggestion?

Thanks

Upvotes: 0

Views: 2208

Answers (2)

rdfleay
rdfleay

Reputation: 83

as more robustly explained here, using...

my.data.frame %>% filter(.data[[myName]] == 1) ...

df60 <- df %>% filter(.df[[term]] == "60 months")
df30 <- df %>% filter(.df[[term]] == "30 months")

..or here

ssP <- mutate( nino, PHASE = ifelse(PHASE == "E", "N","L"))

which for your df ..

df60 <- mutate( df, term = ifelse(term == "60 months"))
df30 <- mutate( df, term = ifelse(term == "30 months"))

Upvotes: 0

Bulat
Bulat

Reputation: 6979

I cannot reproduce your problem:

df <- data.frame(
  id = c(1, 2, 3),
  val = c("60 months", "36 months", "60 months")
)

df[df$val == "60 months", ]
# df$val == "60 months"
# 1  1 60 months
# 3  3 60 months
df[which(df$val == "60 months"),]
# df$val == "60 months"
# 1  1 60 months
# 3  3 60 months

Upvotes: 1

Related Questions