简体   繁体   中英

extracting the second observation from a character vector in a data frame

Extract the second observation from a c() vector in a data frame.

I have some data which looks like:

                          splitNames
1  , grupo, modelo, s.a.b., de, c.v.
2                         , gymboree
3                           , cerner
4     , stellus, capital, investment
5         , cambium, learning, group
6               , cornell, companies
7                      , the, boeing
8                        , wd-40, co
9                         , glencore
10                    , the, valspar

I want to extract grupo , gymboree , cerner , stellus , cambium , Cornell , the , wd-40 , Glencore and the from the data. Currently I can do it but it only extracts grupo from the data. y %>% mutate(splitNames[[1]][[2]])

Data:

structure(list(splitNames = list(c("", "grupo", "modelo", "s.a.b.", 
"de", "c.v."), c("", "gymboree"), c("", "cerner"), c("", "stellus", 
"capital", "investment"), c("", "cambium", "learning", "group"
), c("", "cornell", "companies"), c("", "the", "boeing"), c("", 
"wd-40", "co"), c("", "glencore"), c("", "the", "valspar"))), class = "data.frame", row.names = c(NA, 
-10L))

Based on your data structure, you could use:

sapply(data$splitNames, function(x) x[2])

 [1] "grupo"    "gymboree" "cerner"   "stellus"  "cambium"  "cornell" 
 [7] "the"      "wd-40"    "glencore" "the" 

We can alo use [ without anonymous function

sapply(data$splitNames, `[`, 2)
#[1] "grupo"    "gymboree" "cerner"   "stellus"  "cambium"  "cornell"  "the"      "wd-40"    "glencore" "the" 

Since you are using the Tidyverse anyway you could also do it this way:

library(purrr)
       
map_chr(data$splitNames, 2)
#>  [1] "grupo"    "gymboree" "cerner"   "stellus"  "cambium"  "cornell" 
#>  [7] "the"      "wd-40"    "glencore" "the"

Created on 2020-07-14 by the reprex package (v0.3.0)

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