“Index Match” In R Studio (multiple columns, across rows)

六月ゝ 毕业季﹏ 提交于 2020-06-28 04:04:29

问题


I'm working with a fairly large data set (100k rows) and want to replicate the Excel Index Match function in R Studio.

I'm looking for a way to create a new column that will pull a value from an existing column ("1995_Number"), if 3 values from three different columns from one year match three values from three columns from another year - independent of the rows, and create a new column ("1994_Number").

Dataframe as example:

dat <- data.frame(`1994_Address` = c("1234 Road", "123 Road", "321 Road"), `1994_ZipCode` = c(99999, 99999, 11111), `1994_Bank Name` = c("JPM", "JPM", "WF"), `1995_Address` = c("123 Road", "1234 Road", "321 Road"), `1995_ZipCode` = c(99999, 99999, 11111), `1995_Bank Name` = c("JPM", "JPM", "WF"), `1995_Number` = c(1, 2, 3), check.names = F, stringsAsFactors = F)

The newly created column 1994_Number should say (2, 1, 3)


回答1:


A possible solution would include the match function from base. Toghether with dplyr the following works:

library(dplyr)
dat <- data.frame(`1994_Adress` = c("1234 Road", "123 Road", "321 Road"),
                  `1994_ZipCode` = c(99999, 99999, 11111),
                  `1994_Bank Name` = c("JPM", "JPM", "WF"),
                  `1995_Adress` = c("123 Road", "1234 Road", "321 Road"),
                  `1995_ZipCode` = c(99999, 99999, 11111),
                  `1995_Bank Name` = c("JPM", "JPM", "WF"),
                  `1995_Number` = c(1, 2, 3), check.names = F, stringsAsFactors = F)
dat %>%
  mutate(`1994_Number` = ifelse(`1994_Adress` %in% `1995_Adress` & 
                                  `1994_ZipCode` %in% `1995_ZipCode` &
                                  `1994_Bank Name` %in% `1995_Bank Name`, 
                                dat[match(dat$`1994_Adress`, dat$`1995_Adress`), "1995_Number"], NA))

#    1994_Adress 1994_ZipCode 1994_Bank Name 1995_Adress 1995_ZipCode 1995_Bank Name 1995_Number 1994_Number
# 1   1234 Road        99999            JPM    123 Road        99999            JPM           1           2
# 2    123 Road        99999            JPM   1234 Road        99999            JPM           2           1
# 3    321 Road        11111             WF    321 Road        11111             WF           3           3


来源:https://stackoverflow.com/questions/61795811/index-match-in-r-studio-multiple-columns-across-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!