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

孤人 提交于 2019-12-02 07:41:33

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

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.

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