过滤r中的data.frame字符列

时间:2018-06-07 21:05:38

标签: r dataframe character

我有一个可变项,其中包括贷款期限,只有两种类型:" 36个月"和#34; 60个月"。我想过滤我的数据集df并为这些类别创建两个不同的子集。

我尝试过使用命令子集,过滤器等等,但它没有用。

代码我尝试df1 –> df[which(df$term == "36 months"),]df1 –> filter(df, term == "36 months") df1–>df[df$term %in% c("36 months"), ]以及其他方式,但始终选择零行。

head(loan_data$term)

[1]" 36个月" " 60个月" " 36个月" " 36个月" " 60个月" " 36个月"

有什么建议吗?

由于

2 个答案:

答案 0 :(得分:1)

我无法重现您的问题:

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

答案 1 :(得分:0)

更强有力地解释here,使用...

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

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

...或here

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

哪个适合您的 df ..

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