简体   繁体   中英

Convert Vector in Table in R

I am new to R . We are using dataset of Trip Advisor for getting values like "Value", "OverAll", "Rooms" etc. in each designated Array. The result is as follows

Value <- as.numeric(c("4","3","5","2.5"))

Overall <- as.numeric(c("4","4.5","2","3"))

Rooms <- as.numeric(c("3","4","2","2"))

I want to get values in Table like.

Value    4    3     5     2.5

Overall    4    4.5    2    3

Rooms    3    4     2     2

I tried to convert it into 2D Array as well as table(Value,Overall,Rooms) . Converting to array led to an error, and table() is not changing it into my required format. Please guide where I am wrong.

Use rbind

rbind(Value = c("4","3","5","2.5"),
      Overall = c("4","4.5","2","3"),
      Rooms = c("3","4","2","2"))

        [,1] [,2]  [,3] [,4] 
Value   "4"  "3"   "5"  "2.5"
Overall "4"  "4.5" "2"  "3"  
Rooms   "3"  "4"   "2"  "2"  

Since you manipulates score here (TripAdvisor notes) , it is better to convert them to numeric, before creating the matrix:

rbind(Value = as.numeric(c("4","3","5","2.5")),
      Overall = as.numeric(c("4","4.5","2","3")),
      Rooms =as.numeric( c("3","4","2","2")))

       [,1] [,2] [,3] [,4]
Value      4  3.0    5  2.5
Overall    4  4.5    2  3.0
Rooms      3  4.0    2  2.0

If you want data frame:

data.frame(Value=Value,Overall=Overall,Rooms=Rooms)

Or matrix:

 rbind(Value=Value,Overall=Overall,Rooms=Rooms)

Note that as you have made your data by

Value <- c("4","3","5","2.5")
Overall <- c("4","4.5","2","3")
Rooms <- c("3","4","2","2")

instead of

Value <- c(4,3,5,2.5)
Overall <- c(4,4.5,2,3)
Rooms <- c(3,4,2,2)

you get characters instead of numbers. Now if you do some modelling, the values "4", "3" etc. are taken as factors (see ?factors ), so you cannot have value such as 3.5, which I think you would like to have as you also have 2.5 etc.

The function table is used for tables of counts and things like that:

table(c("a","b","a","d","abc","b","b"))
  a abc   b   d 
  2   1   3   1 

May I suggest you to collect the JSON data-set, then you can easily parse them, as R is very strong for extracting data from JSON. You may visit: https://www.rstudio.com/online-learning/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM