R data.frame删除因子[重复]

时间:2022-09-15 15:03:25

This question already has an answer here:

这个问题在这里已有答案:

I have a data.frame as the following :

我有一个data.frame如下:

myPhoneHTML

     X1            X2    X3     X4     X5 X6       X7

  1 Brand         Model Price Screen Weight GB     Date

  2 Apple       iPhone7 24500    4.7    138 32 20160916

  3   HTC         OneM8 21900      5    160 16 20140328

  4   HTC         OneS9  9990      5    158 32 20160617

  5  ASUS ZenFoneDeluxe  8990    5.5    170 16 20150827

  6  ASUS   ZenFoneZoom 15990    5.5    185 64 20151201

How do i take Brand~Data as factor instead of x1~x7?

我如何将Brand~Data作为因子而不是x1~x7?

like this :

喜欢这个 :

    Brand         Model Price Screen Weight GB     Date

1   Apple       iPhone7 24500    4.7    138 32 20160916

2   HTC         OneM8 21900    5.0    160 16 20140328

3   HTC         OneS9  9990    5.0    158 32 20160617

4  ASUS ZenFoneDeluxe  8990    5.5    170 16 20150827

5  ASUS   ZenFoneZoom 15990    5.5    185 64 20151201

(There's no x1~x7 but Brand~Data) Thanks!

(没有x1~x7但是品牌〜数据​​)谢谢!

1 个解决方案

#1


4  

We can assign the first row as the column names and then remove the first row

我们可以将第一行指定为列名,然后删除第一行

colnames(myPhoneHTML) <- myPhoneHTML[1,]
myPhoneHTML <- myPhoneHTML[-1,]
myPhoneHTML[] <- lapply(myPhoneHTML, function(x) type.convert(as.character(x), as.is = TRUE))

It is not clear how the data is being read. If we use read.csv/read.table, specify the header = TRUE to read the first row as the column name

目前尚不清楚如何读取数据。如果我们使用read.csv / read.table,请指定header = TRUE以读取第一行作为列名

dat <- read.csv("file.csv", header = TRUE, stringsAsFactors = FALSE)

#1


4  

We can assign the first row as the column names and then remove the first row

我们可以将第一行指定为列名,然后删除第一行

colnames(myPhoneHTML) <- myPhoneHTML[1,]
myPhoneHTML <- myPhoneHTML[-1,]
myPhoneHTML[] <- lapply(myPhoneHTML, function(x) type.convert(as.character(x), as.is = TRUE))

It is not clear how the data is being read. If we use read.csv/read.table, specify the header = TRUE to read the first row as the column name

目前尚不清楚如何读取数据。如果我们使用read.csv / read.table,请指定header = TRUE以读取第一行作为列名

dat <- read.csv("file.csv", header = TRUE, stringsAsFactors = FALSE)