Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

dataframe - Stacking columns by pair in R

id <- rep(c(1, 2, 3, 4), 3)
name <- rep(c("a", "b", "c", "d"), 3)
variable_a <- c(1:4, 9:12, 17:20)
variable_b <- c(5:8, 13:16, 21:24)

test1 <- data.frame(id, name, variable_a, variable_b)
question from:https://stackoverflow.com/questions/65865932/stacking-columns-by-pair-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A base R option with reshape

reshape(
  setNames(test,gsub("(\d)(.)","\2.\1",names(test))),
  direction = "long",
  idvar = c("id","name"),
  varying = -(1:2)
)

gives

      id name time variable_a variable_b
1.a.1  1    a    1          1          5
2.b.1  2    b    1          2          6
3.c.1  3    c    1          3          7
4.d.1  4    d    1          4          8
1.a.2  1    a    2          9         13
2.b.2  2    b    2         10         14
3.c.2  3    c    2         11         15
4.d.2  4    d    2         12         16
1.a.3  1    a    3         17         21
2.b.3  2    b    3         18         22
3.c.3  3    c    3         19         23
4.d.3  4    d    3         20         24

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...