2

I'm trying to directly enter the following data into R (which represents a contingency table)

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

My code is this:

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)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pirate
  • 311
  • 1
  • 5
  • 12

2 Answers2

7

Your code is full of basic syntax errors, please try and copy-and-paste directly from the script you are using. (I really hope you have not done this here).

If you combine character and numeric variables in the same vector, it will create a character vector, which is not what you want.

Try something like

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
mnel
  • 113,303
  • 27
  • 265
  • 254
2

Using tribble from tidyverse (see tidyverse tibble for more details)

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
Dan Tarr
  • 209
  • 3
  • 8