D*******a 发帖数: 207 | 1 比如有字典d:
A 1
B 2
C 3
X 5
有向量x:
A
C
X
B
D
翻译完了是这样的:y
1
3
5
2
D
因为字典里面没有D,所以D保留不翻译。可以optionally删除D。直接用语句来完成比
较繁琐,容易出错,如下:
d=c("A","B","C","X","1","2","3","5");
dim(d)=c(4,2)
x=c("A","C","X","B","D")
sapply(x, FUN=function(item) {if(!(item %in% d)) {item} else {d[which(item =
= d[,1]),2]}})
我自己写过一个y=translation(x,d),就是把上面那句话包装一下;但是这样一个常用
的东西我想R里面会有现成的函数的。请指教! | s*****n 发帖数: 2174 | 2 这个其实很简单, 就用names()即可
d <- c(1,2,3,5)
names(d) <- c("A", "B", "C", "X")
x <- c("A", "C", "X", "B", "D")
x[is.element(x, names(d))] <- d[is.element(x, names(d))]
> x
[1] "1" "2" "3" "5" "D" | D*******a 发帖数: 207 | 3 你这个不对,翻译后的顺序错了,不是向量概念了,是set(集合)的概念了。 | s*****n 发帖数: 2174 | 4 小改动一下即可
> d <- c(1,2,3,5)
> names(d) <- c("A", "B", "C", "X")
> x <- c("A", "C", "X", "B", "D")
> x[is.element(x, names(d))] <- d[x[is.element(x, names(d))]]
> x
[1] "1" "3" "5" "2" "D"
【在 D*******a 的大作中提到】![](/moin_static193/solenoid/img/up.png) : 你这个不对,翻译后的顺序错了,不是向量概念了,是set(集合)的概念了。
| w*******n 发帖数: 469 | 5 so nice to read your R code, I like R more than SAS.
【在 s*****n 的大作中提到】![](/moin_static193/solenoid/img/up.png) : 小改动一下即可 : > d <- c(1,2,3,5) : > names(d) <- c("A", "B", "C", "X") : > x <- c("A", "C", "X", "B", "D") : > x[is.element(x, names(d))] <- d[x[is.element(x, names(d))]] : > x : [1] "1" "3" "5" "2" "D"
|
|