Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中关系表的跨度矩阵_R_Plyr_Denormalized - Fatal编程技术网

R中关系表的跨度矩阵

R中关系表的跨度矩阵,r,plyr,denormalized,R,Plyr,Denormalized,我经常在R中使用来自SQL数据库的数据。通常我在SQL中做了很多杂耍,但最近越来越多地使用plyr,我想知道在R中从关系数据表中跨越矩阵是否更容易。这里有一个例子 我有一张像这样的桌子 id question answer 1 6 10 1 4 1 1 5 2003 3 6 2 #reproduce it with dput output: structure(list(resul

我经常在R中使用来自SQL数据库的数据。通常我在SQL中做了很多杂耍,但最近越来越多地使用
plyr
,我想知道在R中从关系数据表中跨越矩阵是否更容易。这里有一个例子

我有一张像这样的桌子

id   question answer
 1        6      10
 1        4       1
 1        5     2003
 3        6       2

 #reproduce it with dput output:
 structure(list(result = c(1, 1, 1, 3), question = c(6, 4, 5, 
 6), answer = c("10", "1", "2003", "2")), .Names = c("id", 
 "question", "answer"), row.names = c("1", "2", "3", "4"), class = "data.frame")
我想将其安排为非标准化矩阵:

id question.6 question.4 question.5
1       10        1          2003
3        2     
等等。。 我在SQL中使用了一个
的CASE WHEN
语法修复了这个问题,但在R中无法做到,例如:

  Select min((case when (question_id` = 6)
  then answer end)) AS `question.6`

dcast
中的
restrape2
将完成该工作:

> z
  id question answer
1  1        6     10
2  1        4      1
3  1        5   2003
4  3        6      2
> dcast(z, id ~ question, value_var = "answer")
  id    4    5  6
1  1    1 2003 10
2  3 <NA> <NA>  2
>z
身份证问题答案
1  1        6     10
2  1        4      1
3  1        5   2003
4  3        6      2
>dcast(z,id~问题,值_var=“答案”)
id 4 5 6
1  1    1 2003 10
2  3    2
试试这个:

> tapply(DF[,3], DF[,-3], identity)
   question
id   4    5  6
  1  1 2003 10
  3 NA   NA  2

也许我应该把它纹在手背上。真不敢相信我写了多少傻瓜函数来涵盖这一点。然后用了一段时间,几个月后又试了一次。哈哈。