简体   繁体   English

R:将数据框x中的行名与数据框y中的列名匹配,以使两个数据框共享的列中的给定变量值

[英]R: match row name in data frame x with column name in data frame y for a given variable value in column shared by the two data frames

Say i have two data frames which looks like the ones below 说我有两个看起来像下面的数据框

> df1
        date firm1 firm2 firm3
1 01-01-2017     1     2    3
2 01-02-2017     4     5    6
3 01-03-2017     7     8    9

> df2
            date
firm1 01-02-2017
firm2 01-01-2017
firm3 01-03-2017

Is it possible to extract a new data frame with the values from df1 where the column name and date value of df1 matches the row name and date of df2? 是否可以使用df1中的值(其中df1的列名和日期值与df2的行名和日期相匹配)提取新的数据帧?

The data frame is was hoping to get would look like: 希望获得的数据帧如下所示:

      Value
firm1     2
firm2     4
firm3     9

Any suggestions would be greatly appreciated! 任何建议将不胜感激!

We can use row/column indexing to extract the values from 'df1' and create a data.frame 我们可以使用row/column索引从'df1'中提取值并创建一个data.frame

df3 <- data.frame(Value = df1[-1][cbind(1:nrow(df1), match(df2$date, df1$date))])
row.names(df3) <- row.names(df2)
df3
#      Value
#firm1     2
#firm2     4
#firm3     9
library(reshape2)
#regenerating the initial datasets
date <- c("01-01-2017","01-02-2017","01-03-2017")
firm1 <- c(1,4,7)
firm2 <- c(2,5,8)
firm3 <- c(3,6,9)
df1 <- data.frame(date,firm1,firm2,firm3)

df1
        date  firm1  firm2  firm3
1: 01-01-2017     1     2     3
2: 01-02-2017     4     5     6
3: 01-03-2017     7     8     9

variable <- c("firm1","firm2","firm3")
date <- c("01-02-2017","01-01-2017","01-03-2017")
df2 <- data.frame(date,variable)

df2
      date      variable
1: 01-01-2017    firm1
2: 01-02-2017    firm2
3: 01-03-2017    firm3

#changing the format from wide to long

df1b <- melt(df1,id.vars = "date")
df1b
       date variable value
1: 01-01-2017    firm1     1
2: 01-02-2017    firm1     4
3: 01-03-2017    firm1     7
4: 01-01-2017    firm2     2
5: 01-02-2017    firm2     5
6: 01-03-2017    firm2     8
7: 01-01-2017    firm3     3
8: 01-02-2017    firm3     6
9: 01-03-2017    firm3     9

res <- merge(df2,df1b,by=c("date","variable"))

res  
    date variable value
1: 01-01-2017    firm2     2
2: 01-02-2017    firm1     4
3: 01-03-2017    firm3     9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM