我有一个包含许多变量的数据框。这是我目前所拥有内容的简化版本:
n_20010_0_0 <- c(1,2,3,4)
n_20010_0_1 <- c(0, -2, NA, 4)
n_20010_0_2 <- c(3, 0, -7, 2)
x <- data.frame (n_20010_0_0, n_20010_0_1, n_20010_0_2)
我创建了一个新变量,返回变量列表中是否有 1:
MotherIllness0 <- paste("n_20010_0_", 0:2, sep = "")
x$MotherCAD_0_0 <- apply(x, 1, function(x) as.integer(any(x[MotherIllness0] == 1, na.rm = TRUE)))
我想将 NA 保留为 0,但我也想重新编码它,以便如果有 -7,则新值是 NA。 这是我尝试过的方法,但它不起作用:
x$MotherCAD_0_0[MotherIllness0 == -7] <- NA
最佳答案
您不需要定义 MotherIllness0
,apply
函数中的参数 1 会处理它。
这里有一行代码可以完成您想要的两件事。
MotherIllness0 <- paste("n_20010_0_", 0:2, sep = "")
x$MotherCAD_0_0<- apply(x[,MotherIllness0], 1, function(x) ifelse(any(x==-7), NA,
as.integer(any(x==1, na.rm=T))))
我假设同时包含 1 和 -7 的行的新变量应为 NA。如果没有,那么这应该有效:
x$MotherCAD_0_0<- apply(x[,MotherIllness0], 1, function(x) ifelse(any(x==1, na.rm=T), 1,
ifelse(any(x==-7), NA, 0)))
请注意,对于上面的示例,这两行应该产生相同的结果。
关于r - 将 NA 分配给列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43770241/