简体   繁体   中英

R loop to list all the values of a variable

As an exercice, I have to create a vector of all the different values of a variable (a$dep). This vector can be created with the code: unique(a$dep)

I need to create this vector using a for loop I wrote a loop that doesn't give the right result but I don't understand where is the problem:

v<-vector()
    for (i in seq_along(a$dep)){
      v<-ifelse(a$dep[i] %in% v, v,c(v,a$dep[i]))
}

Thank you very much for your help !

Based on the description, if we need unique values an if condition is sufficient ie loop over the sequence of 'dep' column if the element is not ( ! ) %in% 'v', append that element to 'v' and update the 'v' by assignment ( <- )

v <- vector()
for(i in seq_along(a$dep)) {if(!a$dep[i] %in% v) v <- c(v, a$dep[i])}

As ifelse requires all arguments to be of same length , 'v' is dynamic in length as we concatenate elements to it, thus, the 'yes', 'no' (always length 1 - a$dep[i] ) mismatches in length.


One option with ifelse would be to initiate a vector 'v' with the same length as the 'dep' column length, then use ifelse to check whether the 'dep' element is %in% the whole vector (return TRUE/FALSE - length 1), then return blank (yes - "" - length 1) or else return the element of 'dep (no - a$dep[i]- length 1)

v <- character(nrow(a))
for(i in seq_along(a$dep)) v[i] <- ifelse(a$dep[i] %in% v, "", a$dep[i])

and then remove the blank elements

v[v != ""]
#[1] "a" "b" "c" "e"

The ifelse is useful as vectorized function and its use would not be optimal here

data

a <- data.frame(dep = c('a', 'b', 'a', 'c', 'e', 'a'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM