How i can shift one row of data frame to first row?

纵然是瞬间 提交于 2019-12-02 17:30:41

问题


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

回答1:


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



回答2:


You could do the following (assuming your ID is the Nth row):

df <- iris # Example of data.frame
myIdrow <- 5 # as an example id row
df2 <- df[c(myIdrow, (1:nrow(df))[-myIdrow]), ]

Although I would recommend to have the ID as column name.



来源:https://stackoverflow.com/questions/44369947/how-i-can-shift-one-row-of-data-frame-to-first-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!