2015-11-24 136 views
0

我有一個非常大的數據集,包括250個字符串和數字變量。我想一個接一個地把一個個的列比較一下。例如,我將比較(差異)第一個變量與第二個變量,第三個與第四個變量,第五個變量與第六個變量等等。
例如(數據集的結構類似於這個例子),我想比較number.x與number.y,day.x與day.y,school.x與school.y等。如何循環遍歷R中的列

number.x<-c(1,2,3,4,5,6,7) 
number.y<-c(3,4,5,6,1,2,7) 
day.x<-c(1,3,4,5,6,7,8) 
day.y<-c(4,5,6,7,8,7,8) 
school.x<-c("a","b","b","c","n","f","h") 
school.y<-c("a","b","b","c","m","g","h") 
city.x<- c(1,2,3,7,5,8,7) 
city.y<- c(1,2,3,5,5,7,7) 
+0

當傳遞給R時,您的花式彎曲引號不起作用。此外,「比較」可能意味着任何事情。 – Frank

+0

與大多數編程語言不同,「。」不表示數據幀或對象的成員:即number.x和number.y是2個完全不同的向量。 當你說比較時,具體是什麼比較?例如,如果輸入'number.y == number.x',您將得到一個與number.x(或number.y)長度相同的向量,其中TRUE和FALSE條目指示它們在哪裏相等。這是你在找什麼? –

+0

感謝您的回覆。例如(對於數字)number.x和number.y之間的差異是否爲0。兩個字符串列之間的比較也意味着我們是否擁有相同的元素。 – shadi

回答

1

你的意思是,這樣的事情?

> number.x == number.y 
[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE 
> length(which(number.x==number.y)) 
[1] 1 
> school.x == school.y 
[1] TRUE TRUE TRUE TRUE FALSE FALSE TRUE 
> test.day <- day.x == day.y 
> test.day 
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE 

編輯:鑑於你上面的例子變量,我們有:

df <- data.frame(number.x, 
      number.y, 
      day.x, 
      day.y, 
      school.x, 
      school.y, 
      city.x, 
      city.y, 
      stringsAsFactors=FALSE) 

n <- ncol(df) # no of columns (assumed EVEN number) 

k <- 1 
comp <- list() # comparisons will be stored here 

while (k <= n-1) { 
     l <- (k+1)/2 
     comp[[l]] <- df[,k] == df[,k+1] 
     k <- k+2 
} 

在這之後,你必須:

> comp 
[[1]] 
[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE 

[[2]] 
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE 

[[3]] 
[1] TRUE TRUE TRUE TRUE FALSE FALSE TRUE 

[[4]] 
[1] TRUE TRUE TRUE FALSE TRUE FALSE TRUE 

要獲得列k之間的比較結果和k+1,你可以看看comp(k+1)/2元素 - 即得到compari列7 & 8之間兒子的結果,你看看comp元素8/2=4

> comp[[4]] 
[1] TRUE TRUE TRUE FALSE TRUE FALSE TRUE 

編輯2:要使比較在數據幀新列:

new.names <- rep('', n/2) 
for (i in 1:(n/2)) { 
    new.names[i] <- paste0('V', i) 
} 

cc <- as.data.frame(comp, optional=TRUE) 
names(cc) <- new.names 

df.new <- cbind(df, cc) 

之後,你有:

> df.new 
    number.x number.y day.x day.y school.x school.y city.x city.y V1 V2 V3 V4 
1  1  3  1  4  a  a  1  1 FALSE FALSE TRUE TRUE 
2  2  4  3  5  b  b  2  2 FALSE FALSE TRUE TRUE 
3  3  5  4  6  b  b  3  3 FALSE FALSE TRUE TRUE 
4  4  6  5  7  c  c  7  5 FALSE FALSE TRUE FALSE 
5  5  1  6  8  n  m  5  5 FALSE FALSE FALSE TRUE 
6  6  2  7  7  f  g  8  7 FALSE TRUE FALSE FALSE 
7  7  7  8  8  h  h  7  7 TRUE TRUE TRUE TRUE 
+0

嗨,感謝您的評論,是的,我正在尋找這個。但問題是因爲我的數據集中有300個變量。我正在尋找一種方法來將一個接一個的列連在一起。你有什麼想法嗎? – shadi

+0

只要我明白:你想比較第1列與第2,3列與第4列,...第k列與第k + 1列,第k + 2列與第k + 3列等等。是否正確? – desertnaut

+0

是的,你是對的。 – shadi