下面的例子显示了向量中某些元素的替换.应该替换的元素由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]
Run Code Online (Sandbox Code Playgroud)
你可以尝试这样使用match....
x <- val[ match( x , key ) ]
Run Code Online (Sandbox Code Playgroud)
这是一个显示它们是如何相同的例子......
# 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"
Run Code Online (Sandbox Code Playgroud)