简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM