【发布时间】:2020-12-22 12:10:05
【问题描述】:
我是 R 和 stackoverflow 菜鸟 - 如果问题不恰当或结构不合理,请原谅。
我正在尝试编写一些 R 代码来将 nrow x ncol 表/数据帧转换为数据帧,每行包括:行号、列号、列 j 中的值、行 i 的原始表/数据框。
我有许多表/数据框,我想用类似的方式处理它们,每个表/数据框都有不同的行数、列数...
因此,在本例中,我有一个 6 行 x 9 列的数据框,我想将其转换为 54 行的数据框:
#create example data
values <- rnorm(54, mean = 75, sd=3)
table_m <- matrix(values, ncol=9)
table <- as.data.frame(table_m)
我目前的代码如下:
##count rows and columns
nrows <- nrow(table)
ncols <- ncol(table)
#set up empty matrix for output
iterations <- nrows * ncols
variables <- 3
output <- matrix(ncol=variables, nrow=iterations)
#set up first empty vector
my_vector_1 = c()
#run first nested for loop to create sequence of nrow * copies of column numbers
for (j in 1:ncol(table))
for (i in 1:nrow(table))
{
my_vector_1[length(my_vector_1)+1] = colnames(table)[j]
}
# add to first column of output
output[,1] <- my_vector_1
# set up second empty vector
my_vector_2 = c()
#run second nested for loop to create sequence of ncol * copies of row numbers
for (j in 1:ncol(table))
for (i in 1:nrow(table))
{
my_vector_2[length(my_vector_2)+1] = rownames(table)[i]
}
# add to second column of output
output[,2] <- my_vector_2
#create third empty vector
my_vector_3 = c()
#run third nested for loop to pull values from original table/dataframe
for (j in 1:ncol(table))
for (i in 1:nrow(table))
{
my_vector_3[length(my_vector_3)+1] = table[i,j]
}
output[,3] <- my_vector_3
所以,这段代码可以正常工作,并且可以满足我的需求……但在我的菜鸟状态下,它是通过大量谷歌搜索拼凑而成的,看起来很不雅。特别是,创建中间向量,然后将它们分配给输出数据帧列似乎有点麻烦 - 但我无法让它工作试图将值直接放入输出数据帧的列中。
非常欢迎任何关于如何改进代码的想法。
提前非常感谢...
【问题讨论】:
-
与 Ben 的回答类似,您可以使用
table %>% mutate(row = row_number()) %>% pivot_longer(cols = -row)和dplyr和tidyr。 -
@RonakShah 您可能想在编辑后添加
library(tidyverse)/edit: obsolete -
这是学习 R 时常见的“错误”,通常是因为认为 R 中的
data.frames 的行为类似于其他语言中的二维数组或表。它没有。for循环很少是更改帧中数据的最有效方法,并且(几乎)迭代地逐行增长帧永远不是一个好主意。 -
感谢@RonakShah 提供最简单的解决方案!也感谢@r2evans 提供帮助的 cmets。非常感谢社区的支持。
标签: r loops for-loop coding-efficiency