R: lapply function over a list (selecting/sub-setting) -


i having difficult time "sub-setting" list.

for example,

test <- data.frame(x = c("5353-66", "55-110-4000","6524-533", "62410-165", "653-520-2410")) test$x <- as.character(test$x)  strsplit(test$x, "-") 

strsplit gives me list below:

[[1]] [1] "5353" "66"    [[2]] [1] "55"   "110"  "4000"  [[3]] [1] "6524" "533"   [[4]] [1] "62410" "165"    [[5]] [1] "653"  "520"  "2410" 

when run lapply(strsplit(test$x, "-"), "[[", 1), gives me first character string each component of list below:

[[1]] [1] "5353"  [[2]] [1] "55"  [[3]] [1] "6524"  [[4]] [1] "62410"  [[5]] [1] "653" 

then... how select entire [[1]] , [[2]] , [[3]]... separately?

for example, want assign test$y[1] c("5353", "66") , test$y[2] c("55" , "110" , "4000") , on.

test$y <- lapply(strsplit(test$x, "-"), "[", 1)  

above line gave me same result.

while can messy it's easy do. on right track adding unlist() , using strsplit() lapply() want.

test$y <- lapply(1:length(test$x),function(i) unlist(strsplit(test$x[[i]],"-")))

test$y[[1]]

[1] "5353" "66"


Comments