n1tk
n1tk

Reputation: 2500

Extract first element non-zero from a vector element

This is the vector i'm looking to work on as a sameple

test <- c (-0.0799 ,  0.0003 , -0.0063 ,  0.0000 , -3.3180 ,  0.0000 ,  0.0000)
v1 <- as.numeric(test)
v1

so first I did split the elements:

l <- split(test, 1)
l

and after just split elements in characters:

a <- -0.0799

b <- as.numeric(strsplit(as.character(a), "")[[1]])
b

Resulting in: [1] NA 0 NA 0 7 9

so the result of b I try to check and extract first non-zero element so will result in: 7

Question: how do I extract first no-zero element?

now a list of list creation from a column: cl <- data$X

mybiglist <- list()
for(i in 1:length(cl){
  print(cl[i])
  f.split <- as.numeric(strsplit(as.character(cl[i]), "")[[1]])
  print(f.split)
  mybiglist[[i]] <- f.split
 }

Only thing left is for each list in the list created to extract the first non-zero value ... and outputing a list and if is NA just keep NA for that cell. Thinking of regex for extracting but i'm unfamiliar with so advanced technique in R, I can extract number or part of string but not as a search, any help will be great.

P.S: Ultimate goal is the apply to a column of a dataframe and use for creating a variable containing this conditions and if condition not met than just place NA, so will be at the end a column for "X" as "X_1" and "Y" as "Y_1" what will have data as follow: if value of each cell of column is non-zero than extract first non-zero element and if is "NA" or "0" than value will be "NA". so first try to figure out how I can do this task and finally just put in a function.

Upvotes: 0

Views: 2563

Answers (1)

n1tk
n1tk

Reputation: 2500

I will post answer in case anybody has same problem/task

  1. create vector and anything what is "0" than will be imouted with "NA"
    cl$X <- abs(cl$X) #absolute value to not have negative sign
    cl$X
    #converting missing to NA
    cl$X[cl$Xt==0] <- NA
    cl$X
    mybiglist <- list()
    for(i in 1:length(cl$X)){
    print(cl$X[i])
    f.split <- as.numeric(strsplit(as.character(cl$X[i]), "")[[1]])
    print(f.split)
    mybiglist[[i]] <- f.split
    }
  1. next will include the the code what takes the linked list [[]] and iterate thru each sublist and subset variables what are > 0 and outputting into a new list new_vector2:
new_vector <- c()
for (i in 1:length(mybiglist)){
if (length(mybiglist[[i]]) > 1) {
 print(i)
new_vector[[i]] <- subset(mybiglist[[i]], mybiglist[[i]] > 0)
} else {
 new_vector[[i]] <- NA
   }
 }
new_vector

extract first position element from each list:

final_var <- lapply(new_vector, `[`, 1) #completed 
final_var

sample output of the vector with 1 element only

Upvotes: 0

Related Questions