如果我正确理解了你的问题,下面有四种方法可以相当于Excel的VLOOKUP
,并使用R
填写:
# load sample data from Q
hous <- 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 the numbers to fill
# the large table
lookup <- unique(hous)
HouseType HouseTypeNo
1 Semi 1
2 Single 2
3 Row 3
5 Apartment 4
以下是使用lookup
表中的值填写largetable
中HouseTypeNo
的四种方法:
第一个merge
英寸的底座:
# 1. using base
base1 <- (merge(lookup, largetable, by = 'HouseType'))
第二种方法是在基底中使用命名向量:
# 2. using base and a named vector
housenames <- 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 package
library(plyr)
plyr1 <- join(largetable, lookup, by = "HouseType")
第四,使用sqldf
包
# 4. using the sqldf package
library(sqldf)
sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo
FROM largetable
INNER JOIN lookup
ON largetable.HouseType = lookup.HouseType")
如果largetable
中的某些房屋类型可能在lookup
中不存在,则将使用左连接:
sqldf("select * from largetable left join lookup using (HouseType)")
其他解决方案也需要相应的改变.
这就是你想做的吗?让我知道你喜欢哪种方法,我会添加 comments .