[英]Move every n rows of a matrix to a new column in R
I have a data structure like the following 我有一个像下面这样的数据结构
stat_names values
stat1 0.3
stat2 0.5
stat_x ...
stat 16 0.8
and I would like to convert it to a similar structure, so that every 4 rows a new column is created and those 4 rows are moved to the new column. 并且我想将其转换为类似的结构,以便每4行创建一个新列,并将这4行移动到新列。
A B C D
stat1 stat5 stat9 stat13
stat2 stat6 stat10 stat11`
... ... ... ...
Where "A", "B", "C", "D" is a a-priori user-defined column names vector. 其中“ A”,“ B”,“ C”,“ D”是先验用户定义的列名向量。
Although this is trivial to do by hand in Excel, I would like to do this in R with a script that can be iterated across multiple inputs. 尽管这在Excel中是手工完成的,但我还是想在R中使用可以跨多个输入迭代的脚本来完成。
Here, I cast the data frame as a matrix and then back to a data frame to produce the desired result. 在这里,我将数据帧转换为矩阵,然后返回到数据帧以产生所需的结果。
# Dummy data frame
df <- data.frame(stat_names = paste("stat", 1:16, sep = " "),
values = runif(16))
# Cast as matrix with 4 rows and then as a data frame
df <- as.data.frame(matrix(df$stat_names, nrow = 4))
# Rename columns
names(df) <- LETTERS[1:ncol(df)]
# A B C D
# 1 stat 1 stat 5 stat 9 stat 13
# 2 stat 2 stat 6 stat 10 stat 14
# 3 stat 3 stat 7 stat 11 stat 15
# 4 stat 4 stat 8 stat 12 stat 16
If you actually want values
in this format, change df$stat_names
to df$values
. 如果您实际上需要这种格式的values
, df$stat_names
更改为df$values
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.