下面的例子显示了向量中某些元素的替换。应该替换的元素由key给出,新值由val给出。您建议在r?
中采用哪种方法 set.seed(1)
x<-sample(1:10,20,T)
key<-1:10
val<-sample(1:3,10,T)
y<-numeric(length(x))
for(i in 1:length(key))
y[x==key[i]]<-val[i]
答案 0 :(得分:6)
您可以尝试使用此类match
....
x <- val[ match( x , key ) ]
这是一个显示它们是如何相同的例子......
# This awkward loop...
set.seed(1)
x<-sample(1:10,20,T)
key<-1:10
val<-sample(1:3,10,T)
y<-numeric(length(x))
for(i in 1:length(key))
y[x==key[i]]<-val[i]
# Gives the same result as...
x <- val[ match( x , key ) ]
# Which can be verified by...
[1] TRUE
all( x == y )
# But you should not be surprised that...
identical( x , y )
[1] FALSE
# Because....
typeof(x)
[1] "integer"
typeof(y)
[1] "double"