需要跨多个变量更改多个值

Need to change multiple values across multiple variables

我有 72 个变量来指示 child 是否能够读取 72 个单词。这些变量实际上编码为 ""(空)、"!""1",分别表示 child 是否得到 正确的单词 未达到,或不正确。值被编码为字符串。这是 tibble

的摘录
lit <- data.frame(rbind(c("1", "", "", ""),
           c("", "1", "1", "1"),
           c("!", "", "", ""),
           c("!", "", "", "")))

lit
  X1 X2 X3 X4
1  1         
2     1  1  1
3  !         
4  !         

我需要将它们分别重新编码为 1NA0 以执行一些统计(例如单词正确的个人计数、均值等)。我期待以下输出:

lit
  X1 X2 X3 X4
1  0  1  1  1
2  1  0  0  0
3 NA  1  1  1
4 NA  1  1  1

我尝试了以下代码

for(k in words) {
if(lit[[k]][lit[[k]] == ""]){
    lit[[k]][lit[[k]]] <- 1
  }
  else {lit[[k]][lit[[k]]] <- 0
     }}

其中 words 实际上是一个向量,其中包含我需要重新编码的变量的名称。在 for 循环中,您会在此处看到编码,我很乐意仅将正确的单词重新编码为 1,将所有其他单词重新编码为 0,尽管带有 NA 的选项是首选。

在 运行 for 循环之后,我收到以下消息:

Error in if (lit[[k]][lit[[k]] == ""]) { : 
  argument is not interpretable as logical
In addition: Warning message:
In if (lit[[k]][lit[[k]] == ""]) { :
  the condition has length > 1 and only the first element will be used

非常感谢任何帮助,特别是如果使用 dplyr,我目前正在努力改进

您可以使用 match() 的结果来索引替换值的向量。

library(dplyr)

lit %>%
  mutate_all(~c(1, NA, 0)[match(.x, c("", "!", "1"))])  

  X1 X2 X3 X4
1  0  1  1  1
2  1  0  0  0
3 NA  1  1  1
4 NA  1  1  1