시나리오 : 섹션에 데이터가있는 CSV 파일이 있습니다 (예 :CSV 섹션을 읽는 방법에 대한 간략한 설명
[차량 데이터]
MPG, CYL, DISP, HP drat, 중량, qsec, VS, AM, 기어, 수화물
21,6,160,110,3.9,2.62,16.46 , 0,1,4,4
21,6,160,110,3.9,2.875,17.02,0,1,4,4
22.8,4,108,93,3.85,2.32,18.61,1,1,4 , 1
21.4,6,258,110,3.08,3.215,19.44,1,0,3,1
18.7,8,360,175,3.15,3.44,17.02,0,0,3,2
18.1,6,225,105,2.76,3.46 ,
14.3,8,360,245,3.21,3.57,15.84,0,0,3,4 ...
20.22,1,0,3,1 [다른 재료]
서식을 용서하십시오. 적어도 의도 된 데이터 형식과 비슷하게 블록 인용을 얻으려면 새로운 라인을 추가해야했습니다. 나는 아래 mtcars를 사용하여 재현 예제를 만들고 여기에 인용 된 동기 코드에 따라 우리가 예를 들어, 우리가 원하는 행을 서브 세트를 쉽게 비트를 한 적이 척 수 있습니다 : this post에서
# Import raw data:
data_raw <- readLines("test.txt")
# find separation line:
id_sep <- which(data_raw=="")
# create ranges of both data sets:
data_1_range <- 4:(id_sep-1)
data_2_range <- (id_sep+4):length(data_raw)
# using ranges and row data import it:
data_1 <- read.csv(textConnection(data_raw[data_1_range]))
data_2 <- read.csv(textConnection(data_raw[data_2_range]))
합니다. 즉, 우리가 채택하고자하는 접근 방식은 한 번에 데이터를 선으로 읽고 원하는 선을 찾은 다음 read.csv를 사용하여 data.frame을 얻는 것입니다.
이제 올해는 2017 년이므로 우리는 겉치레 세상을 포용하고 readLines 대신 read_lines를 사용하고 read.csv 대신 read_csv를 사용하려고합니다.
library(tidyverse)
write_csv(mtcars, "mtcars_local.csv")
# this creates an easily reproduced local file
data_raw <- readLines("mtcars_local.csv")
# henceforth assume we've found the desired rows and subsetted
data_df <- read.csv(textConnection(data_raw))
head(data_df)
mpg cyl disp hp drat wt qsec vs am gear carb
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# whoo hoo, the above is exactly the output we want (replicating
# the original post answer)
data_raw_2 <- read_lines("mtcars_local.csv")
data_df_2 <- read_csv(textConnection(data_raw_2))
#Error in read_connection_(con) :
# Evaluation error: can only read from a binary connection.
그래서 read_csv는 read.csv와 같은 textConnection을 사용하는 것을 좋아하지 않습니다. read_csv에 대한 문서 말할 않습니다
인수 : 질문 (들)
file: Either a path to a file, a connection, or literal data (either a single string or a raw vector).
그래서 :
- 특정 구분 된 섹션을 얻기의 깔끔한 tidyverse 방법이 있나요 에 CSV의 tibble? (라인에서 읽는 것과 중간 단계로 서브 셋팅하는 것을 포함하지 않습니다)
- 또는 각 라인의 문자열의 벡터에서, 어떻게 그들을 tibble로 가져올 수 있습니까?