2012-01-09 48 views

回答

7

這裏更換呼叫strsplit是使用模塊化的算術運算符%%%/%一個有趣的解決方案:

d <- c(2, 101, 34, 25, 8) 
res <- data.frame(digit1 = d %/% 100, 
        digit2 = d %% 100 %/% 10, 
        digit3 = d %% 10) 
# digit1 digit2 digit3 
# 1  0  0  2 
# 2  1  0  1 
# 3  0  3  4 
# 4  0  2  5 
# 5  0  0  8 

注意,它有輕微的 - 但是還算不錯 - 返回的附帶好處每個列的數值爲。如果你這樣做,但是,要因素列,而不是,只是跟進使用此命令:

res[] <- lapply(res, as.factor) 

all(sapply(res, class)=="factor") 
#[1] TRUE 
+1

巧妙。我喜歡。 – 2012-01-09 17:27:52

+0

@RichieCotton - 謝謝。我認爲將整數看作數字而不是字符串感覺像是意想不到的方法是有趣的。 – 2012-01-09 19:00:12

5

使用formatCstrsplit

idNums <- c(2, 101, 34, 25, 8) 
idChars <- formatC(idNums, width = 3, flag = "0") 
idChars <- strsplit(idChars, "") 
data.frame(
    digits1 = sapply(idChars, function(x) x[1]), 
    digits2 = sapply(idChars, function(x) x[2]), 
    digits3 = sapply(idChars, function(x) x[3]) 
) 

這是使用stringr包乾淨了一點。與

str_split_fixed(idChars, "", 3) 
+2

而不是交一個非常類似的解決方案,這裏是我提出的一行代碼:'t(sapply(strsplit(sprintf(「%003d」,idNums),「」),as.integer))' – 2012-01-09 17:30:11

+0

你也可以使用data.frame (do.call(rbind,idChars)),然後在後面添加列名。 – Dason 2012-01-09 17:33:23

3

我覺得裏奇棉花使用formatC的是KEWL,所以我把它組成:

testdat <- read.fwf(textConnection(formatC(idNums, width = 3, flag = "0") ), 
        widths=c(1,1,1), 
        col.names=c("digit1", "digit2", "digit3") 
        ) 
testdat 
#------------ 
    digit1 digit2 digit3 
1  0  0  2 
2  1  0  1 
3  0  3  4 
4  0  2  5 
5  0  0  8