使用向量在RStudio中创建表

时间:2018-03-21 23:16:36

标签: r

我想在 R Studio 中创建下表:

  Students           Percentage Financial Assistance
1 with_Pell_Grant    0.4059046  True                
2 without_Pell_Grant 0.5018954  True                
3 with_loan          0.4053371  False               
4 without_loan       0.2290538  False      

这是我的代码:

Students1 <- c("with_Pell_Grant","without_Pell_Grant","with_loan", "without_loan")
Percentage1 <- c(0.4059046, 0.5018954, 0.4053371, 0.2290538)
financial_assistance1 <- c('True', 'True', 'False', 'False')

setNames(Students1, Percentage1, financial_assistance1)
as.table(setNames(Students1, Percentage1, financial_assistance1))

但是我收到以下错误:

Error in setNames(Students1, Percentage1, financial_assistance1) : 
  unused argument (financial_assistance1) 

我的目标是拥有一个功能表,因此我可以使用ggplot2创建有用的可视化。

ggplot(data = comparison_table) + 
  geom_bar(mapping = aes(x = Students, fill = financial_assistance1))

但是当我以这种方式生成表格时它没有用:

comparison_table <- matrix(c("with_Pell_Grant","without_Pell_Grant","with_loan", "without_loan", 0.4059046, 0.5018954, 0.4053371, 0.2290538, 'True', 'True', 'False', 'False'),ncol=3,byrow=FALSE)
 colnames(comparison_table) <- c("Students", "Percentage", "Financial Assistance")
 rownames(comparison_table) <- c('1','2','3', '4')
 comparison_table <- as.table(comparison_table)
 comparison_table

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

怎么样?
dat <- data.frame(Students1, Percentage1, financial_assistance1, stringsAsFactors = F)
> dat
           Students1 Percentage1 financial_assistance1
1    with_Pell_Grant   0.4059046                  True
2 without_Pell_Grant   0.5018954                  True
3          with_loan   0.4053371                 False
4       without_loan   0.2290538                 False

或者

> cbind.data.frame(Students1, Percentage1, financial_assistance1)
           Students1 Percentage1 financial_assistance1
1    with_Pell_Grant   0.4059046                  True
2 without_Pell_Grant   0.5018954                  True
3          with_loan   0.4053371                 False
4       without_loan   0.2290538                 False