2017-10-01 8 views
1

次の問題に直面しています。私はtitleという列のテーブルを持っています。分割列がR

title列には、To kill a mockingbird (1960)のような値の行が含まれています。

したがって、基本的に列の形式は[title] ([year])です。私が必要とするのは、2つの列:titleyearyearです。

もう1つの問題は、括弧を含むタイトルが含まれている行があります。しかし、 では、基本的に各行の最後の6文字が角かっこで囲まれています。

titleyearの2つの列を作成するにはどうすればよいですか?

私は何を持っていることは次のとおりです。

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つの文字をINGのsubstrを回避することができます。

まず、私たちはあなたのdata.frameを再作成:

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

その後、我々は新しいものを作成します。最初の列、Titledf$Titleから最後の7文字です(末尾のスペースも削除されます)。 2番目の列、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と呼んだテキストファイルの中にあります。そこからデータを読み込み、タイトルと年の2つの列が抽出されたdata.frameにデータが読み込まれます。 OPは明らかにそれを望んでいるようそれから私は一人で()を残し、最後に固定長年から別のタイトルにsubstr()を使用します。

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、削除またはないことができます。