我有来自旧软件的输出,这些软件将每个事务的记录包装成多行。我想将这些行解包到一个平面数据帧中。我已经找到了展开列而不是行的解决方案,并且可以在循环中做我需要的事情,但是输出很大,我更喜欢比循环更快的解决方案。
示例:我从一个.csv文件中将两个事务("tran")中的每个事务(“tran”)的6条信息读入R,这两个事务被包装成四行。
下面的代码表示并模拟了我从.csv文件读入R时的数据:
V1 <- c("tran1.col1", "tran1.col4","tran2.col1", "tran2.col4")
V2 <- c("tran1.col2", "tran1.col5", "tran2.col2", "tran2.col5")
V3 <- c("tran1.col3", "tran1.col6", "tran2.col3", "tran2.col6")
df <- as.data.frame(matrix(c(V1, V2, V3), ncol = 3))我希望将上面的内容转换为以下内容:
X1 <- c("tran1.col1", "tran2.col1")
X2 <- c("tran1.col2", "tran2.col2")
X3 <- c("tran1.col3", "tran2.col3")
X4 <- c("tran1.col4", "tran2.col4")
X5 <- c("tran1.col5", "tran2.col5")
X6 <- c("tran1.col6", "tran2.col6")
df.x <- as.data.frame(matrix(c(X1, X2, X3, X4, X5, X6), ncol = 6))我看过整洁的例程来收集和传播数据文件,以及在重塑中熔化和解算,但据我所知,我需要首先解开行。
发布于 2019-01-02 10:47:39
如果您的所有输入都有6条信息,那么下面的方法应该是可行的。
vec <- as.character(unlist(t(df)))
df.x <- as.data.frame(matrix(vec, ncol = 6, byrow = T))来解释到底发生了什么.
# Transpose the df (to a matrix)
matrix <- t(df)
# Now that the matrix is in this sequence it will allow us to unlist it so
# that it produces a vector in the correct sequence (i.e tran1.col1,
# tran1.col2 .. tran2.col1, tran1.col2)
vec <- unlist(matrix)
# Now we can coerce it back to a data.frame, defining the number of columns
# and creating it by row (rather than column)
df.x <- as.data.frame(matrix(vec, ncol = 6, byrow = T))https://stackoverflow.com/questions/54000596
复制相似问题