我们可以更容易地创建数据,而不是多个步骤
i1 <- grepl('^pub', names(data)) # index for pub columns
i2 <- grepl('^age', names(data)) # index for age columns
data[i1] <- lapply(data[i1], function(x) pmax(round(., 0), 0)) # data rounding
# instead of NA values, replaced with 0 as it is easier to get the column index
循环通过1:6,在
list
,提取与
first
与“pub”的每一行中的值匹配,
cbind
并提取相应的“年龄”值。如果一行中没有匹配项,则它将是na(使用“j2”索引),并分配这些项以在“data”中创建新列。
data[paste0("age_v", 1:6)] <- lapply(1:6, function(i) {
j1 <- max.col(data[i1] == i, 'first')
j2 <- rowSums(data[i1] == i) == 0
data[i2][cbind(seq_len(nrow(data)), j1 *(NA^j2))]
})