1

如果 x >1 但 < 2,我想重新编码列中的值,它将被重新编码为 1

这是我的代码:

neu$b <- lapply(neu$swl.y, function(x) ifelse(x>1 & x<=2, 1, x))

有什么不对吗?

 swl.y

  2.2
  1.2
  3.4
  5.6

我实际上需要重新编码所有值:

  neu$c <- with(neu, ifelse(swl.y>1 & swl.y <=2, 1, swl.y))
  neu$c <- with(neu, ifelse(swl.y>2 & swl.y <=3, 2, swl.y))
  neu$c <- with(neu, ifelse(swl.y>3 & swl.y <=4, 3, swl.y))
  neu$c <- with(neu, ifelse(swl.y>4 & swl.y <=5, 4, swl.y))
  neu$c <- with(neu, ifelse(swl.y>5 & swl.y <=6, 5, swl.y))
  neu$c <- with(neu, ifelse(swl.y>6 & swl.y <=7, 6, swl.y))

我想我知道问题出在哪里。当 R 运行第二行代码时,重新编码的值恢复到以前的值。

4

1 回答 1

3

我们不需要循环单个列。通过使用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 的编辑帖子,如果我们需要多次重新编码,请使用cutfindInterval。在 中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))
于 2015-08-13T14:21:01.657 回答