2017-10-01 1 views
1

다음과 같은 문제가 있습니다. title 란 열이있는 표가 있습니다.분할 열이 R

title 열은 To kill a mockingbird (1960)과 같은 값을 갖는 행을 포함합니다.

기본적으로 열의 형식은 [title] ([year])입니다. 두 개의 열이 필요합니다 : titleyear, year 대괄호가 없습니다.

다른 문제 중 하나는 괄호가 포함 된 제목이있는 행이 있다는 것입니다. 그러나 기본적으로 모든 행의 마지막 6자는 연도를 괄호로 묶습니다.

두 개의 열, titleyear은 어떻게 만듭니 까?

는 내가 가지고있는 것은 :

Books$title <- c("To kill a mockingbird (1960)", "Harry Potter and the order of the phoenix (2003)", "Of mice and men (something something) (1937)") 

title 
To kill a mockingbird (1960) 
Harry Potter and the order of the phoenix (2003) 
Of mice and men (something something) (1937) 

내가해야 할 것은 :

Books$title <- c("To kill a mockingbird", "Harry Potter and the order of the phoenix", "Of mice and men (something something)") 
Book$year <- c("1960", "2003", "1937") 

title            year 
To kill a mockingbird        1960 
Harry Potter and the order of the phoenix   2003 
Of mice and men (something something)    1937 
+0

[재현 가능한 예] (https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) –

답변

2

우리는 지난 6 개 문자를 보내고 주위 substr을 작업 할 수 있습니다.

df <- read.table(h=T, sep="\n", stringsAsFactors = FALSE, 
text=" 
Title 
To kill a mockingbird (1960) 
Harry Potter and the order of the phoenix (2003) 
Of mice and men (something something) (1937)") 

그런 다음 우리는 새로운 하나를 만들 :

먼저 우리는 data.frame하여 다시 작성하십시오. 첫 번째 열 Title은 모두 df$Title이지만 마지막 7 자 (모두 후행 공백을 제거함)입니다. 두 번째 열인 Yeardf$Title의 마지막 6 자이며 공백, 여는 또는 닫는 괄호를 제거합니다. (gsub("[[:punct:]]", ...)도 효과가있었습니다.

data.frame(Title=substr(df$Title, 1, nchar(df$Title)-7), 
      Year=gsub(" |\\(|\\)", "", substr(df$Title, nchar(df$Title)-6, nchar(df$Title)))) 


             Title Year 
1      To kill a mockingbird 1960 
2 Harry Potter and the order of the phoenix 2003 
3  Of mice and men (something something) 1937 

문제가 해결 되었습니까? 나는 것을 assumue

:

0

비슷한 새 열로 저장하는 루프에서 substrRight(df$Title, 6)를 사용하려고 데이터는 어떤 텍스트 파일에서 so.dat이라는 곳에서 데이터를 읽는 곳에서 가져올 수 있습니다. 여기에는 또한 추출 할 제목과 연도의 두 열이 포함되어 있습니다.

titles  <- data.frame(orig = readLines("so.dat"), 
       text = "", yr = "", stringsAsFactors = FALSE) 
titles$text <- substring(titles[ , 1 ], 
       1, nchar(titles[ , 1 ]) - 7) 
titles$yr <- substring(titles[ , 1 ], 
       nchar(titles[ , 1 ]) - 5, nchar(titles[ , 1 ])) 

원래의 데이터가 추가로 필요에 따라 dpending, 제거하거나 할 수는 없습니다 : 그럼 난() 만 영업 이익은 분명히 그들을 원하는대로 떠나 끝에서 고정 길이 대비 제목을 분리 substr()를 사용합니다.