我如何将一行数据帧移到第一行? [英] How i can shift one row of data frame to first row?

查看:91
本文介绍了我如何将一行数据帧移到第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将一个原始数据帧转换为第一个原始数据,我希望id原始数据成为第一个原始数据.在R中.

How i can shift one raw of data frame to first raw, i want the id raw be the first raw. in R.

Sepal.Length Sepal.Width Petal.Length Petal.Width Species

5.1         3.5          1.4         0.2         setosa
4.9         3.0          1.4         0.2         setosa
4.7         3.2          1.3         0.2         setosa
4.6         3.1          1.5         0.2         setosa
5.0         3.6          1.4         0.2         setosa
id           A            B           C            D

推荐答案

我们可以使用grepl基于'Sepal.Length'中的'id'创建逻辑向量,然后通过以下方式设置数据集的列名:在从原始数据集中删除该行的同时提取该行

We can use grepl to create a logical vector based on the 'id' in 'Sepal.Length', then set the column names of the dataset by extracting that row while removing the row from the original dataset

i1 <- grepl("id", df1$Sepal.Length)
setNames(df1[!i1,], unlist(df1[i1,]))
#   id   A   B   C      D
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa

这篇关于我如何将一行数据帧移到第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆