【发布时间】:2015-08-13 14:16:56
【问题描述】:
我想重新编码列中的值 如果 x >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 运行第二行代码时,重新编码的值恢复到以前的值。
【问题讨论】:
-
在更新后的数据集中,条件不匹配,因为没有一个元素满足条件
swl.y>1 & swl.y<=2示例显示 -
刚刚编辑过,我确定我的样本中有满足条件的值。
-
是的,现在可以
with(neu1, ifelse(swl.y>1 & swl.y <=2, 1, swl.y)) #[1] 2.2 1.0 3.4 5.6检查 1.2 是否被 1 替换。只需将其分配给neu1$b <-即可创建新列 -
您能否检查您的列
sw1.y是否为数字。即str(neu)。如果列不是数字。例如,如果是factor,则将其转换为数字。即neu1$sw1.y <- as.numeric(as.character(neu1$sw1.y)) -
完美,这就是我想要的,谢谢!