Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Table from text in R?

Tags:

parsing

r

In R, what would be the best way to separate the following data into a table with 2 columns?

March 09, 2018
0.084752
March 10, 2018
0.084622
March 11, 2018
0.084622
March 12, 2018
0.084437
March 13, 2018
0.084785
March 14, 2018
0.084901

I considered using a for loop but was advised against it. I do not know how to parse things very well, so if the best method involves this process please be as clear as possible.

The final table should look something like this:

https://i.sstatic.net/u5hII.png

Thank you!

like image 397
Henry Walsh Avatar asked Oct 21 '25 15:10

Henry Walsh


1 Answers

Input:

input <- c("March 09, 2018",
"0.084752",
"March 10, 2018",
"0.084622",
"March 11, 2018",
"0.084622",
"March 12, 2018",
"0.084437",
"March 13, 2018",
"0.084785",
"March 14, 2018",
"0.084901")

Method:

library(dplyr)
library(lubridate)
df <- matrix(input, ncol = 2, byrow = TRUE) %>% 
  as_tibble() %>% 
  mutate(V1 = mdy(V1), V2 = as.numeric(V2))

Output:

df
# A tibble: 6 x 2
  V1             V2
  <date>      <dbl>
1 2018-03-09 0.0848
2 2018-03-10 0.0846
3 2018-03-11 0.0846
4 2018-03-12 0.0844
5 2018-03-13 0.0848
6 2018-03-14 0.0849

Use names() or rename() to rename each columns.

names(df) <- c("Date", "Value")
like image 133
Nik Muhammad Naim Avatar answered Oct 23 '25 06:10

Nik Muhammad Naim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!