![](/img/trans.png)
[英]R - how to get vector of strings frequency if i have strings in matrix and their factor levels
[英]How to assign factor levels by the weight of strings in a vector?
我想根據弦的重量分配因子水平。 通常,R似乎按字母順序分配因子水平:
set.seed(54)
x <- sample(1:10, 5000, replace = TRUE)
x <- "levels<-"(as.factor(x), LETTERS[1:10])
> summary(x)
A B C D E F G H I J
524 508 519 489 477 496 507 526 473 481
我可以重新排序因子水平並像這樣重新分配它們:
l <- data.frame(x=summary(x), old.levels=names(summary(x)),
row.names = NULL)
l <- transform(l[order(summary(x)), ],
new.levels=LETTERS[1:10])
levels(x) <- l[order(l$old.levels), 3]
> summary(x)
I G H D B E F J A C
524 508 519 489 477 496 507 526 473 481
但是到此為止,我沒有更改因子值:
> summary(as.factor(as.numeric(x)))
1 2 3 4 5 6 7 8 9 10
524 508 519 489 477 496 507 526 473 481
我怎樣才能聰明地得到自己想要的東西?
factor
默認行為的確是對級別進行排序,然后分配標簽。
set.seed(54)
x <- sample(letters[1:10], 5000, replace = TRUE)
f1 <- factor(x, labels = LETTERS[1:10])
f2 <- factor(x, levels = sort(unique(x)), LETTERS[1:10])
summary(f1)
#> A B C D E F G H I J
#> 524 508 519 489 477 496 507 526 473 481
identical(f1, f2)
#> [1] TRUE
如果只希望按頻率順序分配標簽,則可以通過在創建因子時重新排列標簽來做到這一點:
f3 <- factor(x, levels = sort(unique(x)), LETTERS[1:10][order(table(x))])
summary(f3)
#> I E J D F G B C A H
#> 524 508 519 489 477 496 507 526 473 481
如果要按頻率順序排列標簽,並按字母順序對級別進行排序,請在創建因子時對級別進行排序:
f4 <- factor(x, levels = sort(unique(x))[order(table(x))], LETTERS[1:10])
summary(f4)
#> A B C D E F G H I J
#> 473 477 481 489 496 507 508 519 524 526
由reprex軟件包 (v0.2.0)創建於2018-03-16。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.