Replacing multiple elements from a vector from an index
我有一个名为 Main 的数据框,其中包含经纪人名称及其编号:
1 2 3 | Main <- data.frame( Number = c(3,70,40,8), Broker = c("XP","HSBC","MORGAN STANLEY","UBS")) |
然后,有一个由这些经纪人进行的交易的向量:
1 | Broker <- c(70,70,8,8,8,8,8,8,8,40) |
我想用它们在 Main 中的相应元素替换 Broker 元素,并产生一个输出,如 Broker_Name:
1 | Broker_Name <- c("HSBC","HSBC","UBS","UBS","UBS","UBS","UBS","UBS","UBS","MORGAN STANLEY") |
已经尝试过gsub并合并没有成功。
你想要映射值。有一个功能可以做到这一点:
1 2 3 | 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 2 3 4 5 6 7 8 9 | 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]) } |
你试过合并吗?
1 2 3 4 5 6 7 8 9 10 11 12 | 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) |