R将一长串问卷选择转换为一个数据框,每个问卷有一行
一份问卷被传递给教师,以检查他们的课程偏好。他们必须从大约50个选项中选择20个项目。 结果数据是以下类型的一长串选择: 教师ID,问题ID 我想将其格式化为一个列表,每个教师一行,每个问题一列,可能的值为:0(未选择),1(已选择)。 在(编程语言的)伪代码中R将一长串问卷选择转换为一个数据框,每个问卷有一行,r,R,一份问卷被传递给教师,以检查他们的课程偏好。他们必须从大约50个选项中选择20个项目。 结果数据是以下类型的一长串选择: 教师ID,问题ID 我想将其格式化为一个列表,每个教师一行,每个问题一列,可能的值为:0(未选择),1(已选择)。 在(编程语言的)伪代码中 可能是这样的: iterate list { data [teacher_id] [question_id] = 0 } 以下是示例数据和预期结果: a <- data.frame( Case_ID = c(1,
可能是这样的:
iterate list {
data [teacher_id] [question_id] = 0
}
以下是示例数据和预期结果:
a <- data.frame(
Case_ID = c(1,1,2,2,4,4),
Q_ID = c(3,5,5,8,2,6)
)
a返回一个矩阵
并使用矩阵
索引来完成以下工作:
m <- matrix(0, nrow=3, ncol=8)
rownames(m) <- c(1,2,4)
colnames(m) <- 1:8
idx <-apply(a, 2, as.character)
m[idx] <- 1
m
## 1 2 3 4 5 6 7 8
## 1 0 0 1 0 1 0 0 0
## 2 0 0 0 0 1 0 0 1
## 4 0 1 0 0 0 1 0 0
m注意,您可以将a
视为索引列表,索引本身引用“主数组”中哪些单元格是真的
。
然后,如果你有一个主矩阵,比如说所有0'
s的res
,你可以告诉R
:“在a
中引用的所有元素都应该是1
”
这是在下面完成的
首先,我们创建“主矩阵”
#识别唯一的教师ID
老师们,你想把结果具体地作为一个data.frame还是一个矩阵?仍然不确定是什么,但它对我非常有效。
m <- matrix(0, nrow=3, ncol=8)
rownames(m) <- c(1,2,4)
colnames(m) <- 1:8
idx <-apply(a, 2, as.character)
m[idx] <- 1
m
## 1 2 3 4 5 6 7 8
## 1 0 0 1 0 1 0 0 0
## 2 0 0 0 0 1 0 0 1
## 4 0 1 0 0 0 1 0 0
# identify the unique teacher ID's
teacherIDs <- unique(a$Case_ID)
# count how many teachers there are
numbTeachers <- length(teacherIDs)
# create the column names for the questions
colNames <- c(paste0("Q_", 1:50))
# dim names for matrix. Using T_id for the row names
dnames <- list(paste0("T_", teacherIDs),
colNames)
# create the matrix
res2 <- matrix(0, ncol=50, nrow=numbTeachers, dimnames=dnames)
# create index out of a
indx <- a
indx$Case_ID <- as.numeric(as.factor(indx$Case_ID))
indx <- as.matrix(indx)
# populate those in a with 1
res2[indx] <- 1
res2