I am trying to merge two different data frames.
Id data
T1 100
T2 250
T3 300
T1 T2 T3
1 2 3
Output I am trying to get
Id data component
T1 100 1
T2 250 2
T3 300 3
dat1<-data.frame(Id=c("T1","T2","T3"),data=c(100,250,300))
dat2<-data.frame(T1=1,T2=2,T3=3)
Just transpose dat2
using 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
What about :
if df is your first data.frame and vec is your vector (with names "T1","T2","T3")
note that using match
ensures that everything goes well even if the names are not in the same order in both data.frames.
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
data :
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"))
output :
> df
Id data component
1 T1 100 1
2 T2 250 2
3 T3 300 3
One way would be the following. But, if your data are just like the example, @user2438475 idea is probably the way to go.
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
DATA
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.