从R中的另一列复制行名

时间:2018-12-28 10:24:25

标签: r

我要删除行号并复制第二列

我想删除行号并复制第二列作为行名,但是我收到此错误消息(.rowNamesDF<-(x,值=值错误:'row.names'长度无效)

df是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)

预期结果: >

 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

实际结果

  

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

1 个答案:

答案 0 :(得分:1)

使用

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

这将告诉R row.names在df的第二列中可用