如何使用 R 中我自己的自定义映射将值向量映射到另一个向量 [英] How do I map a vector of values to another vector with my own custom map in R

查看:22
本文介绍了如何使用 R 中我自己的自定义映射将值向量映射到另一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个函数,它的输入是一个由 1s、2s 和 3s 组成的向量,它发送 1 到 .2、2 到 .4 和 3 到 0.5.(输出应该是一个等长的向量.)我该如何实现?

I want a function whose input is a vector of 1s, 2s, and 3s which sends 1 to .2, 2 to .4 and 3 to .5. (The output should be a vector of equal length.) How do I accomplish this?

例如,如果

myVector<-c(1,2,3,2,3,3,1)

然后是函数

mapVector(myVector)

应该返回一个像 (.2,.4,.5,.4,.5,.5,.2) 这样的向量

should return a vector like (.2,.4,.5,.4,.5,.5,.2)

推荐答案

几个选项,全部使用:

myVector<-c(1,2,3,2,3,3,1)

因素

newvals <- c(.2,.4,.5)
newvals[as.factor(myVector)]
#[1] 0.2 0.4 0.5 0.4 0.5 0.5 0.2

命名向量

newvals <- c(`1`=.2,`2`=.4,`3`=.5)
newvals
#  1   2   3 
#0.2 0.4 0.5 

newvals[as.character(myVector)]
#  1   2   3   2   3   3   1 
#0.2 0.4 0.5 0.4 0.5 0.5 0.2 

查找表

mapdf <- data.frame(old=c(1,2,3),new=c(.2,.4,.5))
mapdf$new[match(myVector,mapdf$old)]
#[1] 0.2 0.4 0.5 0.4 0.5 0.5 0.2

<小时>

量化下面@Joe 评论的基准并解决@Ananda 的评论.


Benchmarks to quantify @Joe 's comment below and address @Ananda's comment as well.

myVector <- c(1,2,3,2,3,3,1)
# setup for the benchmarking
test <- sample(myVector,1e6,replace=TRUE)
newvals <- c(.2,.4,.5)
newvalsvec <- c(`1`=.2,`2`=.4,`3`=.5)
mapdf <- data.frame(old=c(1,2,3),new=c(.2,.4,.5))

microbenchmark(
  newvals[as.factor(test)],
  newvalsvec[as.character(test)],
  mapdf$new[match(test,mapdf$old)],
  newvals[test],
  times=10L
)

#Unit: milliseconds
#         expr        min         lq     median         uq        max
#factor        1863.40146 1876.04197 1890.99147 1913.13046 2014.23609
#namedvector   1809.26883 1812.76272 1837.18852 1851.42954 1858.44996
#lookup          38.48697   38.83405   39.90146   69.65140   71.75051
#newvals[test]   34.07380   34.55885   50.61287   65.69495   66.08699

这篇关于如何使用 R 中我自己的自定义映射将值向量映射到另一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆