## 如何在R中完成VLOOKUP和填充(如Excel)？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (78)

```HouseType HouseTypeNo
Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3```

### 2 个回答

```# load sample data from Q
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```

```# 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]))```

```# 3. using the plyr package
library(plyr)
plyr1 <- join(largetable, lookup, by = "HouseType")```

```# 4. using the sqldf package
library(sqldf)
sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo
FROM largetable
INNER JOIN lookup
ON largetable.HouseType = lookup.HouseType")```

`sqldf("select * from largetable left join lookup using (HouseType)")`

```largetable\$HouseTypeNo <- with(lookup,
HouseTypeNo[match(largetable\$HouseType,
HouseType)])```