Ad

How Can I Subset A Character From Character Strings Separated By " " In R?

- 1 answer

I have a list of character strings, and I want so subset the first character of each element in the list. For example, I want to get only "Apr 2017" in the first element of the list instead of "Apr 2017" "masked" "idw2".

Any thoughts?

> idwstr
[[1]]
[1] "Apr 2017" "masked"   "idw2"    

[[2]]
[1] "Aug 2017" "masked"   "idw2"    

[[3]]
[1] "Dec 2017" "masked"   "idw2"    

[[4]]
[1] "Feb 2017" "masked"   "idw2"    

[[5]]
[1] "Jan 2017" "masked"   "idw2"    

[[6]]
[1] "Jul 2017" "masked"   "idw2"    

[[7]]
[1] "Jun 2017" "masked"   "idw2"    

[[8]]
[1] "Mar 2017" "masked"   "idw2"    

[[9]]
[1] "May 2017" "masked"   "idw2"    

[[10]]
[1] "Nov 2017" "masked"   "idw2"    

[[11]]
[1] "Oct 2017" "masked"   "idw2"    

[[12]]
[1] "Sep 2017" "masked"   "idw2"    

> idwstr[[1]]
[1] "Apr 2017" "masked"   "idw2"```
Ad

Answer

To select the first element of each vector in the list, you need to apply function [ to each element with parameter 1:

sapply(idwstr, '[', 1)
Ad
source: stackoverflow.com
Ad