2017-03-29 75 views
1

我有一個大的向量(數據幀的列),其中包含整數1到30的值。我想用1,6到10替換數字1到6,5到11到15與9 ...根據行值分配值

> x3 <- sample(1:30, 100, rep=TRUE) 
> x3 
    [1] 13 24 16 30 10 6 15 10 3 17 18 22 11 13 29 7 25 28 17 27 1 5 6 20 15 15 8 10 13 26 27 24 3 24 5 7 10 6 28 27 1 4 22 25 14 13 2 10 4 29 23 24 30 24 29 11 2 28 23 1 1 2 
[63] 3 23 13 26 21 22 11 4 8 26 17 11 20 23 6 14 24 5 15 21 11 13 6 14 20 11 22 9 6 29 4 30 20 30 4 24 23 29 

正如我所提到,這是在一個數據幀中的柱上,並用上述分配我想創建不同的列。如果我做了以下,我必須做這30次。

myFrame$NewColumn[myFrame$oldColumn==1] <- 1 
myFrame$NewColumn[myFrame$oldColumn==2] <- 1 
myFrame$NewColumn[myFrame$oldColumn==3] <- 1 
... 

最好的方法是什麼?

回答

2

我們可以cut做到這一點(假設你的意思是什麼 '...' 是10,11,12) :

x4 <- cut(x3, 
      breaks = c(seq(1, 30, 5), 30), right = F, include.lowest = T, # generate correct intervals 
      labels = 4 * (0:5) + 1) # number to fill 

# x4 is factor. We should convert it to character first then to the number 
x4 <- as.numeric(as.character(x4)) 
+0

我真不明白標籤有10,11是不是應該是c(1,5,9,13,17)等。 –

+1

對不起。我沒有得到你的邏輯。 – mt1022

+0

這是一個夢幻般的答案! –

1

你嘗試:

myFrame$NewColumn[myFrame$oldColumn > 0 & myFrame$oldColumn< 6] <- 1 
myFrame$NewColumn[myFrame$oldColumn > 5 & myFrame$oldColumn< 11] <- 1 
... 

甚至更​​好:

myFrame$NewColumn <- as.integer((myFrame$oldColumn - 1)/5)) * 4 + 1