首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >#转换行列表前将其解包

#转换行列表前将其解包
EN

Stack Overflow用户
提问于 2019-01-02 10:34:40
回答 1查看 67关注 0票数 0

我有来自旧软件的输出,这些软件将每个事务的记录包装成多行。我想将这些行解包到一个平面数据帧中。我已经找到了展开列而不是行的解决方案,并且可以在循环中做我需要的事情,但是输出很大,我更喜欢比循环更快的解决方案。

示例:我从一个.csv文件中将两个事务("tran")中的每个事务(“tran”)的6条信息读入R,这两个事务被包装成四行。

下面的代码表示并模拟了我从.csv文件读入R时的数据:

代码语言:javascript
复制
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))

我希望将上面的内容转换为以下内容:

代码语言:javascript
复制
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))

我看过整洁的例程来收集和传播数据文件,以及在重塑中熔化和解算,但据我所知,我需要首先解开行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-02 10:47:39

如果您的所有输入都有6条信息,那么下面的方法应该是可行的。

代码语言:javascript
复制
vec <- as.character(unlist(t(df)))
df.x <- as.data.frame(matrix(vec, ncol = 6, byrow = T))

来解释到底发生了什么.

代码语言:javascript
复制
# 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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54000596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档