在R.“高”Income_Level组的平均贷款金额是多少

时间:2018-02-03 17:48:05

标签: r dataframe mean

在R.“高”Income_Level组的平均贷款金额是多少?

Income_Level <- c('High','Low','Low','High',
                  'Low','High','High','High','Low','Low','High','Low')
Loan_Amount <- c(1000,250,300,925,100,750,600,875,150,400,600,250)
Loan_data <- data.frame(Income_Level,Loan_Amount)
Loan_data

我一直在搞乱平均功能,但似乎无法专门找到'High'Evenue_Level组的平均Loan_Amount。这就是我如何描绘这个答案的代码,但它只是没有成功。

mean(Loan_data$Loan_Amount,Loan_data$Income_Level == 'High')

我感谢任何帮助。感谢

3 个答案:

答案 0 :(得分:2)

mean(Loan_data[Loan_data$Income_Level == "High", ]$Loan_Amount)
[1] 791.6667

说明: 首先,我们为高收入者

分配数据框
Loan_data[Loan_data$Income_Level == "High", ]
Income_Level Loan_Amount
1          High        1000
4          High         925
6          High         750
7          High         600
8          High         875
11         High         600

然后我们将Loan_Amount

作为子集
Loan_data[Loan_data$Income_Level == "High", ]$Loan_Amount
[1] 1000  925  750  600  875  600

答案 1 :(得分:1)

使用tidyverse方法:

library(tidyverse)

Income_Level <- c('High','Low','Low','High',
                  'Low','High','High','High','Low','Low','High','Low')
Loan_Amount <- c(1000,250,300,925,100,750,600,875,150,400,600,250)
Loan_data <- data.frame(Income_Level,Loan_Amount)
Loan_data %>% 
    group_by(Income_Level) %>% 
    summarise(Average_Loan_Amount=mean(Loan_Amount,na.rm=TRUE))

结果如下:

# A tibble: 2 x 2
  Income_Level Average_Loan_Amount
  <fct>                      <dbl>
1 High                         792
2 Low                          242

答案 2 :(得分:1)

我认为它与dataframe构造有关。如果您要分析要分析的数据,如果您能够这样做,则它可以工作:

Loan_data2 <- Loan_data[Income_Level == 'High',]
mean(Loan_data2$Loan_Amount)