How to Create Table from text in R?

痴心易碎 提交于 2021-02-10 12:06:38

问题


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.stack.imgur.com/u5hII.png

Thank you!


回答1:


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")



回答2:


data.table::fread can read "...a string (containing at least one \n)...." 'f' in fread stands for 'fast' so the code below should work on fairly large chunks as well.

require(data.table)

x = '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'

o = fread(x, sep = '\n', header = FALSE)
o[, V1L := shift(V1, type = "lead")]
o[, keep := (1:.N)%% 2 != 0 ]

z = o[(keep)]
z[, keep := NULL]
z



回答3:


result = data.frame(matrix(input, ncol = 2, byrow = T), stringsAsFactors = FALSE)
result
#               X1       X2
# 1 March 09, 2018 0.084752
# 2 March 10, 2018 0.084622
# 3 March 11, 2018 0.084622
# 4 March 12, 2018 0.084437
# 5 March 13, 2018 0.084785
# 6 March 14, 2018 0.084901

You should next adjust the names and classes, something like this:

names(result) = c("date", "value")
result$value = as.numeric(result$value)
# etc.

Using Nik's nice 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"
)


来源:https://stackoverflow.com/questions/49292019/how-to-create-table-from-text-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!