将数据框从行 id 重新排列为列 id

时间:2021-07-20 19:12:56

标签: r

假设我创建了一个数据框

id <- c("a","b","c","d","e","f")
a <- c(6,4,3,6,4,9)
b <- c(8,5,2,9,0,1)

df <- cbind.data.frame(id,a,b)

输出为

   id x y
1  a 6 8
2  b 4 5
3  c 3 2
4  d 6 9
5  e 4 0
6  f 9 1

这当然是我的实际问题的一个较小的可重现版本。在我的实际场景中,我通过以下方式从多个 .xlsx 文件创建了一个数据框

files <- list.files(path = "Discharge", pattern = "*_SUMQH.xls", full.names = T)

strm_data <- sapply(files, read_xlsx, simplify=FALSE) %>% 
  bind_rows(.id = "id")

strm_data <- as.data.frame(strm_data[,-(7:19)])
strm_data <- na.omit(strm_data)

row.names(strm_data) <- NULL

我想要的是按照以下方式排列数据框

  id x y  id x y id x y id x y  id x y id x y
1 a  6 8  b  4 5  c 3 2 d  6 9  e  4 0  f 9 1

2 个答案:

答案 0 :(得分:3)

试试下面的基本 R 代码,使用 Initializing... Scanning... Progress: 20 % Progress: 40 % Progress: 60 % Progress: 80 % Progress: 100 % Files Compared: c:\zap: 5 c:\zap2: 5 4 duplicates found comparing 10 total files + cbind

split

答案 1 :(得分:2)

这是非常基本的解决方案:

cbind(df[1,], df[2,], df[3,], df[4,], df[5,], df[6,])

输出:

  id x y id x y id x y id x y id x y id x y
1  a 6 8  b 4 5  c 3 2  d 6 9  e 4 0  f 9 1