R-两列比较

时间:2018-07-19 20:40:23

标签: r

我是R编程的新手。我正在尝试对两篇文章进行专栏讨论。一栏提供了已经接受住房贷款(以“是”或“否”)的客户的价值,另一栏提供了有关从银行获得个人贷款(以“是”或“否”)的人的信息。

现在我想知道谁同时吸纳了两个客户?

我能够算出客户,但是却无法思考。

让我的数据框为k,列为housingpersonal

k <- housing personal
         yes      yes
          no      yes
         yes       no
         yes      yes  
         yes      yes
         yes      yes 
          no      yes
          no       no

我如何找到同时拥有住房和个人贷款的人数?

2 个答案:

答案 0 :(得分:2)

我想快速完成的最好方法是创建两个向量,分别是“住房”和“个人”:

housing <- c("yes", "yes", "no", "yes", "yes", "no", "yes", "yes")
personal <- c("yes", "yes", "yes", "yes", "no", "yes", "no", "no")

创建名为“ k”的数据框:

k <- data.frame(housing, personal)
k

  housing personal
1     yes      yes
2     yes      yes
3      no      yes
4     yes      yes
5     yes       no
6      no      yes
7     yes       no
8     yes       no

然后使用“ with()”函数评估您的数据。

with(k, table(housing, personal))

       personal
housing no yes
    no   0   2
    yes  3   3

答案 1 :(得分:0)

  

我如何找到同时拥有住房和个人贷款的人数?

你可以

df <- data.frame(
  housing = c("yes", "yes", "no", "yes", "yes", "no", "yes", "yes"), 
  personal = c("yes", "yes", "yes", "yes", "no", "yes", "no", "no"))
sum(df$housing == "yes" & df$personal == "yes")
#R [1] 3