Yao Qiang
Yao Qiang

Reputation: 33

How can I get my numbers from a character separately in R?

enter image description here

newdata <- "1311 1381 1382 1311 1222 1221 2819 2869 2911 2879 5171 5172 6719 1311 1381 1382 2899 2833 2879 2869 2819 1311 1311 1381 1382 2911 5541 6719 2911 2865 2821 2822 2819 5171 5172 5541 1311"

class(newdata)
[1] character

As is shown in the picture, I have a dataset, one of the data is newdata, it is a character.

I would like to know how to get the numbers in the string separately. Ultimately, I would like to get a list such as

[1311,1381,1382,1311,1222,1221,....]

Upvotes: 1

Views: 55

Answers (2)

cephalopod
cephalopod

Reputation: 1906

How does this work for you:

 library(tidyverse)

newdata <- "1311 1381 1382 1311 1222 1221 2819 2869 2911 2879 5171 5172 6719 1311 1381 1382 2899 2833 2879 2869 2819 1311 1311 1381 1382 2911 5541 6719 2911 2865 2821 2822 2819 5171 5172 5541 1311"

    str_split(newdata, " ") %>% map(., as.numeric)   # for list output
    str_split(newdata, " ") %>% map(., as.numeric) %>% bind_cols() # for df/tibble
    str_split(newdata, " ") %>% map(., as.numeric) %>% bind_cols() %>% .[["V1"]] #for vector

Upvotes: 3

Maurits Evers
Maurits Evers

Reputation: 50668

I'm not sure if the suggestions in the comments resolved your issue, but another possibility is to use strsplit.

Let's consider a character vector

newdata <- c(
    "1311 1381 1382 1311 1222 1221", 
    "2819 2869 2911 2879 5171 5172 6719 1311 1381 1382 2899 2833")

Then we can do

lst <- lapply(newdata, function(x) as.numeric(unlist(strsplit(x, " "))))
lst
#[[1]]
#[1] 1311 1381 1382 1311 1222 1221
#
#[[2]]
# [1] 2819 2869 2911 2879 5171 5172 6719 1311 1381 1382 2899 2833

The result is a list of numeric vectors

str(lst)
#List of 2
# $ : num [1:6] 1311 1381 1382 1311 1222 ...
# $ : num [1:12] 2819 2869 2911 2879 5171 ...

Upvotes: 0

Related Questions