简体   繁体   中英

R combine data frame columns and transpose into new data frame

I have a series of data frames from which I wish to construct a new data frame in which each row represents one of the original data frames and the columns elements of the row data. ie:

data1 <- c("bill",1,"a","b")
data2 <- c("bob",2,"a","a")
data3 <- c("bert",3,"c","b")
data4 <- c("bill",1,"b","b")
data5 <- c("bob",2,"b","a")
data6 <- c("bert",3,"a","b")


file1 <- rbind(data1,data2,data3)
file2 <- rbind(data4,data5,data6)

whith this model data I would like a data frame such as this:

      bill    bob    bert
file1  a b    a a     c b
file2  b b    b a     a b

where each row represents a file and each column header is a row from these files "bill", "bob", "bert" etc. containing data from the 3rd and 4th columns of the files.

Is there an easy way to achieve this?

Thanks,

Matt

Another way:

z <- list(file1=file1,file2=file2)
res <- t(sapply(z, function(d) paste(d[,3],d[,4])))
colnames(res) <- file1[,1]

res
#        bill  bob   bert 
# file1 "a b" "a a" "c b"
# file2 "b b" "b a" "a b"

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.

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