敢發誓這個當我在寫下面的憎惡沒有工作,但現在這樣:
## self contained example:
txt <- "col1 col2
Bob John
Tom Bob
Frank Jane
Jim Bob
Tom Bob"
dat <- read.table(textConnection(txt), header = TRUE)
只是計算組獨特的水平和強迫每個colX
的因素:
> dat3 <- dat
> lev <- as.character(unique(unlist(sapply(dat, levels))))
> dat3 <- within(dat3, col1 <- factor(col1, levels = lev))
> dat3 <- within(dat3, col2 <- factor(col2, levels = lev))
> str(dat3)
'data.frame': 5 obs. of 2 variables:
$ col1: Factor w/ 6 levels "Bob","Tom","Frank",..: 1 2 3 4 2
$ col2: Factor w/ 6 levels "Bob","Tom","Frank",..: 5 1 6 1 1
> data.matrix(dat3)
col1 col2
[1,] 1 5
[2,] 2 1
[3,] 3 6
[4,] 4 1
[5,] 2 1
[原文:展示如何愚蠢複雜和模糊的人可以寫R代碼時有人試圖真的很難] 不知道這是特別ELEG螞蟻(它不是),而是......
我們先不公開的數據:
tmp <- unlist(dat)
然後計算出獨特的水平
lev <- as.character(unique(tmp))
,然後重組tmp
(從上面)返回到與原始數據相同的維度,轉換爲data.frame(保留字符串),放在這個數據幀上,創建一個上面計算出的級別lev
的因子,最後強制轉換爲數據幀。
dat2 <- data.frame(lapply(data.frame(matrix(tmp, ncol = ncol(dat)),
stringsAsFactors = FALSE),
FUN = factor, levels = lev))
其中給出:
> dat2
X1 X2
1 Bob John
2 Tom Bob
3 Frank Jane
4 Jim Bob
5 Tom Bob
> sapply(dat2, levels)
X1 X2
[1,] "Bob" "Bob"
[2,] "Tom" "Tom"
[3,] "Frank" "Frank"
[4,] "Jim" "Jim"
[5,] "John" "John"
[6,] "Jane" "Jane"
> data.matrix(dat2)
X1 X2
[1,] 1 5
[2,] 2 1
[3,] 3 6
[4,] 4 1
[5,] 2 1
整潔,乾淨及快捷。好的。恕我直言更好回答@Gavin張貼,雖然我寧願`data.frame(lapply(...`解決方案,出於純粹的懶惰。 – aL3xa 2011-01-31 20:31:36