簡體   English   中英

如何遍歷R中的列

[英]how to loop through columns in R

我有一個非常大的數據集,包括250個字符串和數字變量。 我想一起比較另一列。 例如,我將比較第一個變量與第二個變量,比較第三個變量與第四個變量,第五個變量與第六個變量,依此類推。
例如(數據集的結構類似於此示例),我想比較number.x和number.y,day.x和day.y,school.x和school.y等。

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) 

你的意思是這樣的?

> 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

要獲取列kk+1之間的比較結果,請查看comp(k+1)/2元素-即,要獲取列7和8之間的比較結果,請查看comp元素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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM