Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将数据帧的一行移到第一行?_R_List_Dataframe_Transfer_Shift - Fatal编程技术网

R 如何将数据帧的一行移到第一行?

R 如何将数据帧的一行移到第一行?,r,list,dataframe,transfer,shift,R,List,Dataframe,Transfer,Shift,如何将数据帧的一个raw转换为第一个raw,我希望id raw是第一个raw。在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

如何将数据帧的一个raw转换为第一个raw,我希望id raw是第一个raw。在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

您可以执行以下操作(假设您的ID是第n行):


df我们可以使用
grepl
根据“sepl.Length”中的“id”创建逻辑向量,然后通过提取该行并从原始数据集中删除该行来设置数据集的列名

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

i1所需的输出是什么?您想将所讨论的行作为标题吗?是的,我想成为给定csv的标题您可以
data.table::fread(“given.csv”,skip=N)
其中N是要跳过的所需行数pi想将id raw作为标题raw我做到了,但所有元素都转换为NA!!怎么了@请检查您的数据的
str
。我假设这都是
字符
class@AgriiEnginee您可以首先将列转换为
字符
ie.
df1[]
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