s****y 发帖数: 297 | 1 比如我有一列变量如下:
x <- c("d",rep("a",2),"c",rep("b",6),rep("c",3),"a","a","b",rep("d",8))
这样x 为:"d" "a" "a" "a" "a" "a" "c" "b" "b" "b" "b" "b" "b" "c" "c" "c" "a
" "a" "b" "d" "d" "d" "d" "d" "d" "d" "d"
x有四种值:"d" "a" "c" "b"
我想做的事情是:当某一种值的个数少于5个的时候,将它替换成统一的字符“o”.
这样结果将会是:"d" "o" "o" "o" "b" "b" "b" "b" "b" "b" "o" "o" "o" "o" "o"
"b" "d" "d" "d" "d" "d" "d" "d" "d"
也就是原数据中a和c全部被替换成了o。
我能想到的是用for 循环做对每种值逐一替换。
请大牛们指点一下:能否避免用for循环,直接用什么命令就可以解决的?
因为数据太庞大,用for循环的话时间太长了。。。。
非常感谢!!! | s*****n 发帖数: 2174 | 2 temp <- tapply(x, x, length)
x[x %in% names(temp)[temp < 5]] <- "o"
"a
"
【在 s****y 的大作中提到】 : 比如我有一列变量如下: : x <- c("d",rep("a",2),"c",rep("b",6),rep("c",3),"a","a","b",rep("d",8)) : 这样x 为:"d" "a" "a" "a" "a" "a" "c" "b" "b" "b" "b" "b" "b" "c" "c" "c" "a : " "a" "b" "d" "d" "d" "d" "d" "d" "d" "d" : x有四种值:"d" "a" "c" "b" : 我想做的事情是:当某一种值的个数少于5个的时候,将它替换成统一的字符“o”. : 这样结果将会是:"d" "o" "o" "o" "b" "b" "b" "b" "b" "b" "o" "o" "o" "o" "o" : "b" "d" "d" "d" "d" "d" "d" "d" "d" : 也就是原数据中a和c全部被替换成了o。 : 我能想到的是用for 循环做对每种值逐一替换。
| l*********s 发帖数: 5409 | 3
so cool
【在 s*****n 的大作中提到】 : temp <- tapply(x, x, length) : x[x %in% names(temp)[temp < 5]] <- "o" : : "a : "
| s****y 发帖数: 297 | |
|