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
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.
来源:https://stackoverflow.com/questions/44369947/how-i-can-shift-one-row-of-data-frame-to-first-row