如何在 R 函数中使用 lapply 并转换回 int 格式?
How to use lapply and convert back to int format in R function?
我有测验数据想在 R 中打分,所以我写了一个 ScoreQuiz 函数:
ScoreQuiz <- function(x) {
#Q1 Ans: C; Q2 Ans: D
x$Q1_Score <- lapply(x[,"Q1"], function(x) {as.integer(x == "C")} )
x$Q2_Score <- lapply(x[,"Q2"], function(x) {as.integer(x == "D")} )
## Doesn't work
## x$Q1_Score <- unlist(x$Q1_Score)
score.list <- c("Q1_Score", "Q2_Score")
# commented because of error
#x$Total_Score <- apply(x[score.list], 1, sum)
return(x)
}
df <- data.frame("SubID" = 1:12, "Q1" = c("A","C","D"), "Q2"= c("D","A","B"))
ScoreQuiz(df)
结果
x$Q1_Score <- lapply(x[,"Q1"], function(x) {as.integer(x == "C")} )
returns 一个列表
$ Q1_Score:List of 12
..$ : int 0
..$ : int 1
所以我无法计算函数内的总分。
但是,我可以在函数外取消列出,然后计算总分。
是否可以在函数内部取消列出,或者更好的是,我得到 Q1_Score 而不是首先使用列表?
在这种情况下你不需要 lapply
:
ScoreQuiz <- function(x) {
x$Q1_Score <- as.integer(x$Q1 == 'C')
x$Q2_Score <- as.integer(x$Q2 == 'D')
return(x)
}
str(ScoreQuiz(df))
#'data.frame': 12 obs. of 5 variables:
# $ SubID : int 1 2 3 4 5 6 7 8 9 10 ...
# $ Q1 : chr "A" "C" "D" "A" ...
# $ Q2 : chr "D" "A" "B" "D" ...
# $ Q1_Score: int 0 1 0 0 1 0 0 1 0 0 ...
# $ Q2_Score: int 0 0 1 0 0 1 0 0 1 0 ...
我有测验数据想在 R 中打分,所以我写了一个 ScoreQuiz 函数:
ScoreQuiz <- function(x) {
#Q1 Ans: C; Q2 Ans: D
x$Q1_Score <- lapply(x[,"Q1"], function(x) {as.integer(x == "C")} )
x$Q2_Score <- lapply(x[,"Q2"], function(x) {as.integer(x == "D")} )
## Doesn't work
## x$Q1_Score <- unlist(x$Q1_Score)
score.list <- c("Q1_Score", "Q2_Score")
# commented because of error
#x$Total_Score <- apply(x[score.list], 1, sum)
return(x)
}
df <- data.frame("SubID" = 1:12, "Q1" = c("A","C","D"), "Q2"= c("D","A","B"))
ScoreQuiz(df)
结果
x$Q1_Score <- lapply(x[,"Q1"], function(x) {as.integer(x == "C")} )
returns 一个列表
$ Q1_Score:List of 12
..$ : int 0
..$ : int 1
所以我无法计算函数内的总分。 但是,我可以在函数外取消列出,然后计算总分。
是否可以在函数内部取消列出,或者更好的是,我得到 Q1_Score 而不是首先使用列表?
在这种情况下你不需要 lapply
:
ScoreQuiz <- function(x) {
x$Q1_Score <- as.integer(x$Q1 == 'C')
x$Q2_Score <- as.integer(x$Q2 == 'D')
return(x)
}
str(ScoreQuiz(df))
#'data.frame': 12 obs. of 5 variables:
# $ SubID : int 1 2 3 4 5 6 7 8 9 10 ...
# $ Q1 : chr "A" "C" "D" "A" ...
# $ Q2 : chr "D" "A" "B" "D" ...
# $ Q1_Score: int 0 1 0 0 1 0 0 1 0 0 ...
# $ Q2_Score: int 0 0 1 0 0 1 0 0 1 0 ...