2011-10-19 75 views
2

我在R A data.frame,像這樣:在數據幀替換列值,不包括在列表中

fruits 
    X1 X2  X3 
    aa kiwi 15 
    ba orange 25 
    cc lemon 23 
    ba apple 17 
    cc lemon 19 
    cc orange 18 
    cc orange 21 
    ba banana 17 

我想替換在列X2的所有值除「橙色」和「檸檬「與」其他「。如何在R中做到這一點?

實施例的數據:

fruits <- structure(list(X1 = structure(c(1L, 2L, 3L, 2L, 3L, 3L, 3L, 2L 
), .Label = c("aa", "ba", "cc"), class = "factor"), X2 = structure(c(3L, 
5L, 4L, 1L, 4L, 5L, 5L, 2L), .Label = c("apple", "banana", "kiwi", 
"lemon", "orange"), class = "factor"), X3 = c(15L, 25L, 23L, 
17L, 19L, 18L, 21L, 17L)), .Names = c("X1", "X2", "X3"), class = "data.frame", row.names = c(NA, 
-8L)) 

回答

5

首先創建一個變量,指示要更改的行。你可以這樣做,例如像這樣:

shouldBecomeOther<-!(fruits$X2 %in% c("orange", "lemon")) 

然後使用該索引:

fruits$X2[shouldBecomeOther]<- "other" 

注意,如果該列是一個因子(極有可能),這將需要一些更多的工作,像這樣:

tmp<-as.character(fruits$x2) 
tmp[shouldBecomeOther]<-"other" 
fruits$x2<-factor(tmp) 
1

什麼:

R> fruits = data.frame(X1 = 1:3, X2 = c("kiwi", "orange", "lemon")) 
R> fruits$X2 = as.character(fruits$X2) 
R> fruits[!(fruits$X2 %in% c("lemon", "orange")),]$X2 = "Other" 
R> fruits 
    X1  X2 
1 1 Other 
2 2 orange 
3 3 lemon 

在上述方案中,我轉換的因素爲 「字符」。你沒有做到這一點,你還可以:

  1. 當你創建一個數據幀,使用參數stringsAsFactors = FALSE
  2. 如果使用read.csv,使用stringsAsFactors
  3. 你一起工作直接因素:

    R> fruits$X2 = factor(fruits$X2, levels = c(as.character(fruits$X2), "Other")) 
    R> fruits[!(fruits$X2 %in% c("lemon", "orange")),]$X2 = "Other" 
    R> fruits 
        X1  X2 
    1 1 Other 
    2 2 orange 
    3 3 lemon 
    

    注意,我在直線延伸的第一因素的水平1.

2

一個簡單的方法是將該因子強制轉換爲一個字符向量,然後確定哪些元素不在所需的類中,並用"other"替換它們,最後強制回到一個因子。

有關於這一主題的兩個變化,第一個使用replace()功能:

transform(fruits, 
      X2 = factor(replace(as.character(X2), 
           list = !X2 %in% c("orange","lemon"), 
           values = "other"))) 

這給:

> transform(fruits, X2 = factor(replace(as.character(X2), 
+          list = !X2 %in% c("orange","lemon"), 
+          values = "other"))) 
    X1  X2 X3 
1 aa other 15 
2 ba orange 25 
3 cc lemon 23 
4 ba other 17 
5 cc lemon 19 
6 cc orange 18 
7 cc orange 21 
8 ba other 17 

或者你可以自己動手完成它:

fruits <- transform(fruits, 
        X2 = {x <- as.character(X2) 
          x[!x %in% c("orange","lemon")] <- "other" 
          factor(x)}) 
> fruits 
    X1  X2 X3 
1 aa other 15 
2 ba orange 25 
3 cc lemon 23 
4 ba other 17 
5 cc lemon 19 
6 cc orange 18 
7 cc orange 21 
8 ba other 17 

我在這裏使用transform(),這樣我們就可以在環境中進行操作不需要使用諸如fruits$X2之類的東西就可以看到X2,這些東西很難輸出。