0

I want delete row number and copy second column

i want delete row number and copy second column for row name, but i get this error message(Error in .rowNamesDF<-(x, value = value) : invalid 'row.names' length)

df is main dataframe of mtcars.csv >

 head(df)
                 V1   V2 V3  V4  V5   V6    V7    V8 V9 V10 V11 V12
1         Mazda RX4 21.0  6 160 110 3.90 2.620 16.46  0   1   4   4
2     Mazda RX4 Wag 21.0  6 160 110 3.90 2.875 17.02  0   1   4   4
3        Datsun 710 22.8  4 108  93 3.85 2.320 18.61  1   1   4   1
4    Hornet 4 Drive 21.4  6 258 110 3.08 3.215 19.44  1   0   3   1
5 Hornet Sportabout 18.7  8 360 175 3.15 3.440 17.02  0   0   3   2
6           Valiant 18.1  6 225 105 2.76 3.460 20.22  1   0   3   1

df <- read.csv(paste(getwd(), "/mtcars.csv",sep=""), sep=",", header = FALSE, stringsAsFactors = FALSE)

class(df)
head(df)
dfmpghp <- cbind(df[2],df[5])

head(df)
class(dfmpghp)
rownames(dfmpghp) <- NULL
head(dfmpghp)
colnames(dfmpghp) <- c("mpg","hp")
head(dfmpghp)
rownames(dfmpghp, do.NULL = TRUE, prefix = "row")
rownames(dfmpghp) <- df[1]
head(dfmpghp)

Expected results: >

 head(dfmpghp)
                   mpg  hp
Mazda RX4         21.0 110
Mazda RX4 Wag     21.0 110
Datsun 710        22.8  93
Hornet 4 Drive    21.4 110
Hornet Sportabout 18.7 175
Valiant           18.1 105

actual results

head(dfmpghp)
   mpg  hp
1 21.0 110
2 21.0 110
3 22.8  93
4 21.4 110
5 18.7 175
6 18.1 105
Hunaidkhan
  • 1,411
  • 2
  • 11
  • 21
ZO-1907
  • 3
  • 3

1 Answers1

1

use

example <- read.csv("Table3.csv",header=T,row.names=2,sep=",")

this will tell R that row.names are available in 2nd column of the df

Hunaidkhan
  • 1,411
  • 2
  • 11
  • 21
  • Please edit the answer: 1) The assignment operator is wrong. 2) `read.csv` does not need `header = TRUE` and `sep = ","` because they already are the default. As for the main point, `row.names = 2`, it's absolutely right. But please edit this. – Rui Barradas Dec 28 '18 at 10:37
  • oh thanks for pointing out, header and separator i have added just to make sure Zo gets the answer in the required format – Hunaidkhan Dec 28 '18 at 10:38
  • Thank you very much but, I get this error: Error in read.table(file = file, header = header, sep = sep, quote = quote, : duplicate 'row.names' are not allowed – ZO-1907 Dec 28 '18 at 11:14
  • first make sure row.names = NULL – Hunaidkhan Dec 28 '18 at 11:33