如果我正確理解了您的問題,下面是四種方法來完成與Excel相同的操作VLOOKUP
然后用R
:
# load sample data from Qhous <- read.table(header = TRUE,
stringsAsFactors = FALSE, text="HouseType HouseTypeNo
Semi 1
Single 2
Row 3
Single 2
Apartment 4
Apartment 4
Row 3")# create a toy large table with a 'HouseType' column # but no 'HouseTypeNo' column (yet)largetable <- data.frame(
HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)# create a lookup table to get t
he numbers to fill# the large tablelookup <- unique(hous)
HouseType HouseTypeNo1 Semi 12 Single 23 Row 35 Apartment
4
下面是四種方法來填充HouseTypeNo
在largetable
中的值。lookup
表:
先與merge
基地:
# 1. using base base1 <- (merge(lookup, largetable, by = 'HouseType'))
第二種方法,基中有命名向量:
# 2. using base and a named vectorhousenames <- as.numeric(1:length(unique(hous$HouseType)))names(housenames) <- unique(hous$HouseType)base2
<- data.frame(HouseType = largetable$HouseType,
HouseTypeNo = (housenames[largetable$HouseType]))
第三,使用plyr
一攬子:
# 3. using the plyr packagelibrary(plyr)plyr1 <- join(largetable, lookup, by = "HouseType")
第四,使用sqldf
包裝
# 4. using the sqldf packagelibrary(sqldf)sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo
FROM largetable
INNER JOIN lookup
ON largetable.HouseType = lookup.HouseType")
如果有可能有些人在largetable
不存在于lookup
然后使用左聯(lián)接:
sqldf("select * from largetable left join lookup using (HouseType)")
對(duì)其他解決方案也需要相應(yīng)的修改。
這就是你想做的嗎?讓我知道你喜歡哪種方法,我會(huì)添加評(píng)論。