R:如何将一行旋转到列中?
我想我了解dplyr pivot_longer()和pivot_wider()函数的基础知识,但是现在我有一个混乱的数据表(最初在excel中):
reprex <- tibble(
Sample = c("Colour","A","B"),
cells1green = c("green","3917","4370"),
cells1red = c("red","267","299"),
cells2green = c("green","4443","7082"),
cells2red = c("red","1438","1694"))
在excel,第2列&amp; 3均为单元格1和第4列&amp; 5均为命名细胞2。我在名称中添加了“绿色”和“红色”,因为R无论如何都会更改重复列名的名称。我想知道是否有一种方法可以将第一个数据行(“绿色”,“红色”,“绿色”,“红色”)转换为列(“颜色”)并融合Cells1 ...列将其融合到一列和单元格2 ...列成一个列。最后一步是pivot_longer最终拥有这张桌子:
reprex_final <- tibble(
Sample = c("A","A","A","A","B","B","B","B"),
Celltype = c("Cells1","Cells1","Cells2","Cells2","Cells1","Cells1","Cells2","Cells2"),
Colour = c("green","red","green","red","green","red","green","red"),
Signal = c(3917,267,4443,1438,4370,299,7082,1694))
也许有人对如何进行有一个想法。那将非常有帮助。我希望我提供足够的信息。
I think I understand the basics of the dplyr pivot_longer() and pivot_wider() functions, but now I have a messy data table (originally in excel):
reprex <- tibble(
Sample = c("Colour","A","B"),
cells1green = c("green","3917","4370"),
cells1red = c("red","267","299"),
cells2green = c("green","4443","7082"),
cells2red = c("red","1438","1694"))
In excel, Columns 2 & 3 are both named cells1 and Columns 4 & 5 are both named cells2. I added "green" and "red" to the names as R changes the name of a duplicate column name anyway. I'm wondering if there is a way to turn just the first data row ("green","red","green","red") into a column ("Colour") and fuse the cells1... columns into one column and the cells2... columns into one column. The last step would be to pivot_longer to eventually have this table:
reprex_final <- tibble(
Sample = c("A","A","A","A","B","B","B","B"),
Celltype = c("Cells1","Cells1","Cells2","Cells2","Cells1","Cells1","Cells2","Cells2"),
Colour = c("green","red","green","red","green","red","green","red"),
Signal = c(3917,267,4443,1438,4370,299,7082,1694))
Maybe somebody has an idea about how to proceed. That would be very helpful. I hope I provided enough information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个选项是首先摆脱第一行,然后使用
pivot_longer
喜欢:One option would be to first get rid of the first row and use
pivot_longer
like so: