Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.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_Sna - Fatal编程技术网

如何在R中将数据帧转换为对计数?

如何在R中将数据帧转换为对计数?,r,sna,R,Sna,我是R的新手,我正在为这门课做最后的作业。我在整理数据时遇到了一些问题。 例如,我有如下数据帧 StudentId table_wk1 table_wk2 table_wk3 0034 1 1 2 0067 1 1 1 0098 1 2 2 0079 2 2 1 我想要实现的是将这个数据帧转换

我是R的新手,我正在为这门课做最后的作业。我在整理数据时遇到了一些问题。 例如,我有如下数据帧

StudentId table_wk1 table_wk2 table_wk3
0034       1           1          2
0067       1           1          1
0098       1           2          2
0079       2           2          1  
我想要实现的是将这个数据帧转换成以下数组。当两个学生选择同一张桌子时,他们之间会有一个计数,因此如下所示:

0034  0067  2
0034  0098  2
0034  0079  0
0067  0098  1
0067  0079  1
0098  0079  1

谢谢大家!!如果我的问题不够清楚,请告诉我。这是我在这里的第一个问题。

如果我正确理解您的请求,那么当两个学生ID之间的
表wk
值相同时,计数将打开

下面的代码基本上为学生ID的组合创建了一个新的数据帧(您也可以为此使用
gtools
combinat
包),然后根据两个组合的侧面的比较来计算结果

# Generate data
df <- data.frame(StudentId = c("0034", "0067", "0098", "0079"),
                 table_wk1 = c(1, 1, 1, 2),
                 table_wk2 = c(1, 1, 2, 2),
                 table_wk3 = c(2, 1, 2, 1),
                 stringsAsFactors = F)

# Process data
df2 <- as.data.frame(t(combn(df$StudentId, 2)), stringsAsFactors = F)
df2.1 <- merge(df2[-2], df, by.x = 'V1', by.y = 'StudentId', sort = F)
df2.2 <- merge(df2[-1], df, by.x = 'V2', by.y = 'StudentId', sort = F)
df2.2 <- df2.2[match(df2$V2, df2.2$V2),]  # Solve the sorting issue due to merge

# Create result
df2$Result <- rowSums(df2.1[-1] == df2.2[-1])
#生成数据

df首先创建所有可能的学生组合

df$StudentId = as.character(df$StudentId) 
df_new=data.frame(t(combn(df$StudendId,2)))

> df_new
    X1   X2
 1 0034 0067
 2 0034 0098
 3 0034 0079
 4 0067 0098
 5 0067 0079
 6 0098 0079
现在,使用apply函数并循环通过df_new中的每一行,将2个studentId与df中相应的行进行匹配,并找出两行在哪些列中相等

 df_new$Value_Count = apply(df_new,1, function(x) sum(df[df$StudendId == x[1],2:4] == df[df$StudendId == x[2],2:4]))


> df_new
   X1   X2   Value_Count
 1 0034 0067           2
 2 0034 0098           2
 3 0034 0079           0
 4 0067 0098           1
 5 0067 0079           1
 6 0098 0079           1

谢谢!这对我的问题很有帮助!