我运行以下代码,p
是加载的数据框。
a <- sort(table(p$Title))
a1 <- as.data.frame(a)
tail(a1, 7)
a
Maths 732
Science 737
Physics 737
Chemistry 776
Social Science 905
null 57374
88117
我想对上面的数据帧结果进行一些操作。我想在数据框中添加列名。我尝试了colnames功能。
colnames(a1) <- c("category", "count")
我收到以下错误:
Error in `colnames<-`(`*tmp*`, value = c("category", "count")) :
attempt to set 'colnames' on an object with less than two dimensions
请建议。
答案 0 :(得分:3)
正如我在你的问题的评论中所说,这些类别是rownames。一个可重复的例子:
# create dataframe p
x <- c("Maths","Science","Physics","Chemistry","Social Science","Languages","Economics","History")
set.seed(1)
p <- data.frame(title=sample(x, 100, replace=TRUE), y="some arbitrary value")
# create the data.frame as you did
a <- sort(table(p$title))
a1 <- as.data.frame(a)
结果数据框:
> a1
a
Social Science 6
Maths 9
History 10
Science 11
Physics 12
Languages 15
Economics 17
Chemistry 20
查看数据框a1
的维度,您可以得到:
> dim(a1)
[1] 8 1
表示您的数据框有8行1列。尝试为a1
数据帧分配两个列名将导致错误。
您可以通过两种方式解决问题:
1 :仅使用colnames(a1) <- c("count")
2 :将rownames转换为类别列,然后指定列名:
a1$category <- row.names(a1)
colnames(a1) <- c("count","category")
结果数据框:
> a1
count category
Social Science 6 Social Science
Maths 9 Maths
History 10 History
Science 11 Science
Physics 12 Physics
Languages 15 Languages
Economics 17 Economics
Chemistry 20 Chemistry
您可以使用rownames(a1) <- NULL
删除rownames。这给出了:
> a1
count category
1 6 Social Science
2 9 Maths
3 10 History
4 11 Science
5 12 Physics
6 15 Languages
7 17 Economics
8 20 Chemistry