我正在尝试合并两个不同的数据框。
Id data
T1 100
T2 250
T3 300
T1 T2 T3
1 2 3
输出我想要
Id data component
T1 100 1
T2 250 2
T3 300 3
答案 0 :(得分:2)
dat1<-data.frame(Id=c("T1","T2","T3"),data=c(100,250,300))
dat2<-data.frame(T1=1,T2=2,T3=3)
使用dat2
t(dat2)
data3<-data.frame(dat1,component=t(dat2))
> data3<-data.frame(dat1,component=t(dat2))
> data3
Id data component
T1 T1 100 1
T2 T2 250 2
T3 T3 300 3
答案 1 :(得分:1)
怎么样:
如果df是你的第一个data.frame而vec是你的向量(名称为“T1”,“T2”,“T3”)
请注意,即使两个data.frames中的名称顺序不同,使用match
也可确保一切顺利。
df$component<-vec[match(df$Id,names(vec))] # if vec is a vector
df$component<-unlist(vec[1,match(df$Id,colnames(vec))]) # if vec is a one row data.frame
数据:
df<-structure(list(Id = structure(1:3, .Label = c("T1", "T2", "T3"),
class = "factor"), data = c(100L, 250L, 300L)),
.Names = c("Id","data"), class = "data.frame", row.names = c(NA, -3L))
vec<-structure(1:3, .Names = c("T1", "T2", "T3"))
输出:
> df
Id data component
1 T1 100 1
2 T2 250 2
3 T3 300 3
答案 2 :(得分:1)
一种方式如下。但是,如果您的数据就像示例那样,那么@ user2438475的想法可能就好了。
library(dplyr)
library(tidyr)
gather(mydf2, variable, component) %>%
left_join(mydf, ., by = c("Id" = "variable"))
# Id data component
#1 T1 100 1
#2 T2 250 2
#3 T3 300 3
数据强>
mydf <- structure(list(Id = structure(1:3, .Label = c("T1", "T2", "T3"
), class = "factor"), data = c(100L, 250L, 300L)), .Names = c("Id",
"data"), class = "data.frame", row.names = c(NA, -3L))
mydf2 <- structure(list(T1 = 1L, T2 = 2L, T3 = 3L), .Names = c("T1", "T2",
"T3"), class = "data.frame", row.names = c(NA, -1L))