r

# r - 如何加入ColumnA =（ColumnB

``````df1 <- data.frame(ID=c(5,4,3,2), CASE=c("A","B","C","D"))
df2 <- data.frame(ID=c(6,5,4,3), RESULT=c("ResultA","ResultB","ResultC","ResultD"))
``````

``````df_result<- data.frame(ID_df1=c(5,4,3,2), CASE=c("A","B","C","D"), RESULT=c("Result5","Result4","Result3","Result2"))
``````

``````df_result <- merge ( x = df1, y = df2, by.x = ID , by.y = ID - 1 , all.x = TRUE)
``````

Karibuu

203
Maurits Evers 2019-07-03 21:12

``````library(tidyverse)
left_join(df1, df2 %>% mutate(ID = ID - 1)) %>%
mutate(RESULT = str_replace(RESULT, "^(.+)[A-Z]\$", paste0("\\1", ID)))
#Joining, by = "ID"
#  ID CASE  RESULT
#1  5    A Result5
#2  4    B Result4
#3  3    C Result3
#4  2    D Result2
``````

``````left_join(df1, df2 %>% mutate(ID = ID - 1))
#  ID CASE  RESULT
#1  5    A ResultA
#2  4    B ResultB
#3  3    C ResultC
#4  2    D ResultD
``````

``````merge(df1, transform(df2, ID = ID - 1), by = "ID")
#  ID CASE  RESULT
#1  2    D ResultD
#2  3    C ResultC
#3  4    B ResultB
#4  5    A ResultA
``````

``````transform(
merge(df1, transform(df2, ID = ID - 1), by = "ID"),
RESULT = paste0(substr(RESULT, 1, nchar(as.character(RESULT)) - 1), ID))
#  ID CASE  RESULT
#1  2    D Result2
#2  3    C Result3
#3  4    B Result4
#4  5    A Result5
``````