如何在R中完成VLOOKUP和填充(如Excel)?我有一個大約105000行30列的數據集。我有一個分類變量,我想把它分配給一個數字。在Excel中,我可能會用VLOOKUP然后填滿。我要怎么做同樣的事R?本質上,我所擁有的是HouseType變量,我需要計算HouseTypeNo..以下是一些樣本數據:HouseType HouseTypeNoSemi 1Single 2Row 3Single 2Apartment 4Apartment 4Row 3
3 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
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
sqldf("select * from largetable left join lookup using (HouseType)")

手掌心
TA貢獻1942條經驗 獲得超3個贊
match()
:
largetable$HouseTypeNo <- with(lookup, HouseTypeNo[match(largetable$HouseType, HouseType)])
lookup
.

不負相思意
TA貢獻1777條經驗 獲得超10個贊
qdapTools::lookup
%l%
## Replicate Ben's data:hous <- structure(list(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"), HouseTypeNo = c(1L, 2L, 3L, 2L, 4L, 4L, 3L)), .Names = c("HouseType", "HouseTypeNo"), class = "data.frame", row.names = c(NA, -7L))largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)## It's this simple:library(qdapTools)largetable[, 1] %l% hous
- 3 回答
- 0 關注
- 905 瀏覽
添加回答
舉報
0/150
提交
取消