从索引中的向量替换多个元素

时间:2019-01-28 21:54:56

标签: r indexing gsub

我有一个名为Main的数据框,其中包含经纪人名称及其编号:

 Main <- data.frame(
   Number = c(3,70,40,8), 
   Broker = c("XP","HSBC","MORGAN STANLEY","UBS"))

然后,这些经纪人进行了一系列交易:

Broker <- c(70,70,8,8,8,8,8,8,8,40)

我想用Main中的对应元素替换Broker元素,并产生类似于Broker_Name的输出:

Broker_Name <- c("HSBC","HSBC","UBS","UBS","UBS","UBS","UBS","UBS","UBS","MORGAN STANLEY")

已经尝试了gsub并没有成功合并。

3 个答案:

答案 0 :(得分:2)

您要映射值。有一个功能可以做到这一点:

library(dplyr)
Broker <- c(70,70,8,8,8,8,8,8,8,40)
Broker_Name <- mapvalues(Broker,Main$Number,as.character(Main$Broker))

答案 1 :(得分:0)

您是否尝试过合并?

Main <- data.frame(Number = c(3,70,40,8), Broker =      c("XP","HSBC","MORGAN STANLEY","UBS"))

Broker_Num <- c(70,70,8,8,8,8,8,8,8,40)



Broker_Name <- as.character(merge(as.data.frame(Broker_Num),Main,
                     by.y="Number",
                     by.x="Broker_Num",
                     all.x=T,
                     all.y=F,
                     sort=F)$Broker)

答案 2 :(得分:0)

您可以尝试以下解决方案:

Broker_Name <- c(1:length(Broker))

for(ii in 1:length(Broker)) {

  x <- Broker[ii]

  Broker_Name[ii] <- as.character(Main[Main[,1] == x,2])

  }