我们不需要循环单个列。通过使用lapply(neu$swl.y
,我们将列的每个元素作为list
元素,我们可能不需要。该函数ifelse
是矢量化的,可以直接在 'swl.y' 列上使用 OP 帖子中提到的逻辑条件。
neu$b <- with(neu, ifelse(swl.y>1 & swl.y <=2, 1, swl.y))
否则,我们将“b”列创建为“swl.y”,并根据逻辑条件更改“b”的值。
neu$b <- neu$swl.y
neu$b[with(neu, swl.y>1 & swl.y <=2)] <- 1
为了更好地理解 OP 代码的问题,我们可以检查lapply
lapply(neu$swl.y, function(x) x) #similar to `as.list(neu$swl.y)`
#[[1]]
#[1] 3
#[[2]]
#[1] 0
#[[3]]
#[1] 0
#[[4]]
#[1] 2
#[[5]]
#[1] 1
输出是 a list
,列中的每个元素都作为list
元素。在列表上使用ifelse
可能不是最佳的,因为它是矢量化的(上面已经提到过)。但是,假设如果我们这样做ifelse
lapply(neu$swl.y, function(x) ifelse(x>1 & x<=2, 1, x))
#[[1]]
#[1] 3
#[[2]]
#[1] 0
#[[3]]
#[1] 0
#[[4]]
#[1] 1
#[[5]]
#[1] 1
可以将Adata.frame
视为list
具有相同长度的列表元素。所以,根据上面的输出,这应该是一个 5 列 1 行的 data.frame。通过分配到单个列“b”,我们将创建一个list
包含 5 个列表元素的列。
neu$b <- lapply(neu$swl.y, function(x) ifelse(x>1 & x<=2, 1, x))
str(neu)
#'data.frame': 5 obs. of 2 variables:
#$ swl.y: int 3 0 0 2 1
#$ b :List of 5
# ..$ : int 3
# ..$ : int 0
# ..$ : int 0
# ..$ : num 1
# ..$ : int 1
但是,这不是我们想要的。补救措施是什么?一种方法是使用sapply/vapply
而不是lapply
返回vector
输出,因为长度相同,或者我们unlist
使用lapply
输出来创建vector
neu$b <- sapply(neu$swl.y, function(x) ifelse(x>1 & x<=2, 1, x))
str(neu)
#'data.frame': 5 obs. of 2 variables:
# $ swl.y: int 3 0 0 2 1
# $ b : num 3 0 0 1 1
更新
根据 OP 的编辑帖子,如果我们需要多次重新编码,请使用cut
或findInterval
。在 中cut
,我们可以指定breaks
并且还有其他参数labels
可以返回或不返回默认标签。
with(neu1, cut(swl.y, breaks=c(-Inf,1,2,3,4,5,6,Inf), labels=F)-1)
#[1] 2 1 3 5
数据
set.seed(48)
neu <- data.frame(swl.y=sample(0:5, 5, replace=TRUE))
#newdata
neu1 <- structure(list(swl.y = c(2.2, 1.2, 3.4, 5.6)),
.Names = "swl.y", class = "data.frame", row.names = c(NA, -4L))