在R中的表中转换向量

时间:2013-03-13 14:14:03

标签: r

我是 R 的新手。我们使用Trip Advisor的数据集来获取每个指定数组中的“Value”,“OverAll”,“Rooms”等值。 结果如下

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"))

我想在表格中获取值。

Value    4    3     5     2.5

Overall    4    4.5    2    3

Rooms    3    4     2     2

我尝试将其转换为2D数组以及table(Value,Overall,Rooms)。转换为数组导致错误,table()未将其更改为我所需的格式。请指导我错的地方。

3 个答案:

答案 0 :(得分:3)

使用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"  

由于你在这里操作得分(TripAdvisor备注),最好在创建矩阵之前将它们转换为数字:

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

答案 1 :(得分:3)

如果你想要数据框:

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

或矩阵:

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

请注意,您已通过

制作了数据
Value <- c("4","3","5","2.5")
Overall <- c("4","4.5","2","3")
Rooms <- c("3","4","2","2")

而不是

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

你得到的是字符而不是数字。现在,如果你进行一些建模,将值“4”,“3”等作为因子(参见?factors),因此你不能拥有诸如3.5之类的值,我认为你想拥有它也有2.5等。

函数table用于计数表和类似的事情:

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

答案 2 :(得分:1)

我建议您收集JSON数据集,然后您可以轻松解析它们,因为R非常强大,可以从JSON中提取数据。 您可以访问:enter image description here