Home > Enterprise >  Character value to numeric vector in dataframe
Character value to numeric vector in dataframe

Time:07-07

From a dataframe I get a character vector of a column by: arrange by date, time and group_by date

fall_hc %>% arrange(a_dat,AZeit) %>% group_by(a_dat) %>%
        mutate(time_vec = str_c(snzeit,collapse= ",")) %>% 
        ungroup() %>% 
        filter(!is.na(time_vec))

This results in character vectors like:

x <- c("5, 31, 16, 64, 9, 10, 31") 

I need a numeric vector from this x within a dataframe: 5 31 16 64 9 10 31.
because I want to calculate diff(x): 26 -15 48 -55 1 21.
and further process this to calculate the number of negativ differences.

CodePudding user response:

You can change that x into a numeric vector in the following way:

x <- c("5, 31, 16, 64, 9, 10, 31") 

as.numeric(unlist(strsplit(x, ", ")))

#> [1]  5 31 16 64  9 10 31

Created on 2022-07-06 by the reprex package (v2.0.1)

CodePudding user response:

Keep numbers as numeric in a list:

mtcars %>% 
  group_by(cyl) %>% 
  summarise(x = list(mpg))
# # A tibble: 3 x 2
#         cyl x         
#      <dbl> <list>    
#    1     4 <dbl [11]>
#    2     6 <dbl [7]> 
#    3     8 <dbl [14]>

Then we can do below on the list of numbers:

mtcars %>% 
  group_by(cyl) %>% 
  summarise(x = list(mpg)) %>% 
  group_by(cyl) %>% 
  summarise(xDiffSum = sum(diff(unlist(x))))
# # A tibble: 3 x 2
#      cyl xDiffSum
#   <dbl>    <dbl>
# 1     4    -1.40
# 2     6    -1.3 
# 3     8    -3.7 
  • Related