2

我正在尝试将以下数据直接输入到R中(代表列联表)

Area        School    Coffeshop    Hospitals    Parks    Totatl  
Washington     142          120           20       20       302   
Seattle        120          140           30       40       330 
Total          262          260           50       60       632

我的代码是这样的:

n<-c("Area","School","Cofeeshop","Hospitals","Parks","Total") 
x<-c("Washington",142,120,20,20,302)
y<-c("Seattle",120,140,30,40,330)
z<-c("Total",262,260,50,60,631)
data<-cbind(n,x,y,z)
data<-data.frame(data)
4

2 回答 2

6

您的代码充满了基本的语法错误,请尝试直接从您正在使用的脚本中复制和粘贴。(我真的希望你没有在这里这样做)。

如果您将字符和数值变量组合在同一个向量中,它将创建一个字符向量,这不是您想要的。

尝试类似的东西

vec_names <-c("School", "Cofeeshop", "Hospitals", "Parks", "Total") 
Washington <- c(142, 120, 20, 20, 302)
Seattle<-c(120, 140, 30, 40, 330)
Total <-  c(262, 260, 50, 60, 631)

ctable <- rbind(Washington, Seattle, Total)
colnames(ctable) <- vec_names

# ctable is a matrix at the moment, with the rownames identifying 
# Washington etc

ctable_df <- data.frame(ctable)

# ctable_df is now a data.frame.
# if you want area as a column in your data.frame (not just row.names)
CTABLE <- data.frame(area= rownames(ctable_df), ctable_df, row.names = NULL)
CTABLE
        area School Cofeeshop Hospitals Parks Total
1 Washington    142       120        20    20   302
2    Seattle    120       140        30    40   330
3      Total    262       260        50    60   631
于 2012-10-30T02:35:02.763 回答
2

使用 tidyverse 中的 tribble(有关详细信息,请参阅tidyverse tibble

install.packages("tidyverse")
library(tidyverse)
ctable <-
tribble(
  ~Area, ~School, ~Coffeeshop, ~Hospitals, ~Parks, ~Total,
  "Washington", 142, 120, 20, 20, 302,
  "Seattle", 120, 140, 30, 40, 330,
  "Total", 262, 260, 50, 60, 631
)
ctable
# A tibble: 3 x 6
  Area       School Coffeeshop Hospitals Parks Total
  <chr>       <dbl>      <dbl>     <dbl> <dbl> <dbl>
1 Washington    142        120        20    20   302
2 Seattle       120        140        30    40   330
3 Total         262        260        50    60   631
于 2018-10-13T01:58:15.923 回答