Match row names and column names to values in another data frame

前端 未结 1 2004
耶瑟儿~
耶瑟儿~ 2020-12-21 05:23

I have two data frames as follows :

df1 <- t(data.frame(seq(1,6,by=1),seq(6,1,by=-1)))    
colnames(df1) <- c(\"A\",\"B\",\"C\",\"D\",\"E\",\"F)    
ro         


        
相关标签:
1条回答
  • 2020-12-21 06:08

    We can use merge with melt. The melt returns a three column data.frame, merge it with the second dataset to create the new column

    library(reshape2)
    merge(df2, melt(df1), by.x = c("Vector1", "Vector2"), by.y = c("Var2", "Var1"))
    

    Or a base R option would be to get the numeric index with match after pasteing the 'df2' rowwise (do.call(paste) and get the pasted column names and row names of 'df1' using outer. Using the numeric index, we get the values in 'df1' to create the 'Newcol'

    df2$Newcol <- df1[match(do.call(paste, df2), 
                           t(outer(colnames(df1), rownames(df1), FUN = paste)))]
    df2$Newcol
    #[1] 1 5 3 3 5 1 1 5 3 3 5 1
    
    0 讨论(0)
提交回复
热议问题