R - 随机选择变量并按行操作它们

R - Randomly selecting variables and manipulating them on a row-wise basis

我正在尝试遍历数据框的每一行,随机 select 一半的变量,并将该特定行的变量设置为 NA

例如,对于下面的 mydf 数据集,我希望我的第一行随机 select 3 个变量(比如 QBQEQF) 并将他们的分数设置为 NA,然后在第二行再次设置(比如 QAQDQE),依此类推:

library(tibble)
mydf <- tibble(QA = rnorm(100),
QB = rnorm(100), 
QC = rnorm(100), 
QD = rnorm(100), 
QE = rnorm(100), 
QF = rnorm(100))

我的尝试,但它似乎没有做任何事情:

vars <- names(mydf)
for (i in nrow(mydf)){
  miss_vars <- sample(vars, 3)
  for (j in miss_vars) {
     mydf[i,j] <- NA
#mydf[i,][[j]] <- NA #Also tried this.
   }
}

应该是:

for (i in seq_len(nrow(mydf))){
  miss_vars <- sample(vars, 3)
  for (j in miss_vars) {
    mydf[i,][[j]] <- NA
  }
}

试试这个矢量化:

m <- as.matrix(mydf)
n <- 3 # number of randoms to be selected
inds <- cbind(rep(1:nrow(mydf), each=n), c(replicate(nrow(mydf), sample(ncol(mydf), n))))
m[inds] <- NA
res <- as.data.frame(m)

方法如下:

  1. 首先取数据框的矩阵以受益于所需的向量化
  2. 定义每行随机选择的列数
  3. 生成矩阵inds,其中放置了数据框的每一行和相应的随机列
  4. 将这些行和列设置为 NA
  5. 取回数据框

res 中,您将有一个数据框,其中 3 列随机设置为每行 NA。提供的数据框的输出是:

           # QA          QB          QC        QD         QE         QF
# 1  -0.6264538          NA          NA  1.358680 -0.1645236         NA
# 2   0.1836433          NA  0.78213630        NA -0.2533617         NA
# 3          NA          NA  0.07456498        NA  0.6969634  0.3411197
# 4          NA -2.21469989          NA        NA  0.5566632 -1.1293631
# 5          NA  1.12493092  0.61982575        NA         NA  1.4330237
# 6  -0.8204684 -0.04493361          NA        NA         NA  1.9803999
# 7   0.4874291 -0.01619026          NA -0.394290         NA         NA
# 8   0.7383247          NA -1.47075238        NA         NA -1.0441346
# 9          NA  0.82122120          NA  1.100025         NA  0.5697196
# 10         NA  0.59390132  0.41794156        NA         NA -0.1350546

数据

set.seed(1)
mydf <- data.frame(QA = rnorm(10),
QB = rnorm(10), 
QC = rnorm(10), 
QD = rnorm(10), 
QE = rnorm(10), 
QF = rnorm(10))