如果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运行第二行代码时,已编码的值返回到以前的值。
发布于 2015-08-13 14:21:01
我们不需要为一个列循环。通过使用lapply(neu$swl.y,我们将列的每个元素作为list元素,这是我们可能不需要的。函数ifelse是矢量化的,可以直接在列'swl.y‘上使用,并具有OP的post中提到的逻辑条件。
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输出是一个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] 1data.frame可以被视为具有相同长度的列表元素的list。因此,根据上面的输出,这应该是一个有5列和1行的data.frame。通过分析单个列'b',我们将创建一个包含5个list元素的list列。
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))https://stackoverflow.com/questions/31990782
复制相似问题