3

を含むデータフレームがあります

df 
Date        name             score
12/09/2012  Mahesh\nRahul    120
13/09/2012  abc\nxyz\nrep         110
...........................

私は原子を取得するためにこれを試しました

name1=str_split(df[,2],"\n")

しかし、再度関連付ける方法がわかりません。取得できるようにデータフレームを正規化する最良の方法は何ですか

 df 
Date        name     score
12/09/2012  Mahesh   120
12/09/2012  Rahul    120
13/09/2012  abc      110
13/09/2012  xyz      110
13/09/2012  rep      110
...........................

Rで長いデータフレームを正規化するのに役立ちます。

編集

これは単なる再現可能な例であることに注意してください。名前の列に複数の名前があり、名前の数は行ごとに異なります。ありがとうございます。

dput(df) structure(list(Date = structure(1:2, .Label = c("12/09/2012", "13/09/2012 "), class = "factor"), name = structure(c(2L, 1L), .Label = c("abc\nxyz", "Mahesh\nRahul"), class = "factor"), score = structure(c(2L, 1L), .Label = c("110", "120"), class = "factor")), .Names = c("Date", "name", "score"), row.names = c(NA, -2L), class = "data.frame")
4

4 に答える 4

5

これがRベースのソリューションです

アップデート

> Names <- strsplit(df$name, "\n")
> n <- sapply(Names, length)
> data.frame(cbind(apply(df[,-2], 2, function(x) rep(x, n)), 
                   name=unlist(Names)), row.names = NULL)[,c(1,3,2)]
        Date   name score
1 12/09/2012 Mahesh   120
2 12/09/2012  Rahul   120
3 13/09/2012    abc   110
4 13/09/2012    xyz   110
5 13/09/2012    rep   110

どこにdfある:

> dput(df)
structure(list(Date = c("12/09/2012", "13/09/2012"), name = c("Mahesh\nRahul", 
"abc\nxyz\nrep"), score = c(120, 110)), .Names = c("Date", "name", 
"score"), row.names = c(NA, -2L), class = "data.frame")
于 2013-10-29T11:49:37.733 に答える
3

これは比較的簡単に使用できdata.tableます (そして明らかに高速です)。

require( data.table )
dt <- data.table( df )
dt[ , list( name = unlist( strsplit( name , "\n" ) ) ) , by = list( Date , score ) ]
#         Date score   name
#1: 12/09/2012   120 Mahesh
#2: 12/09/2012   120  Rahul
#3: 13/09/2012   110    abc
#4: 13/09/2012   110    xyz

メモとして、私はdf次のデータを取りました(実際のデータに表示されるcharacterクラスよりもクラスに注意してください...factor

df <- read.delim( text = "Date    name    score
12/09/2012  'Mahesh\nRahul'   120
13/09/2012  'abc\nxyz'       110" ,
sep = "" , h = TRUE , quote = "\'" , stringsAsFactors = FALSE )
于 2013-10-29T11:55:25.293 に答える
2

代替に追加するにはscan、文字列を非常に簡単に分離しrepcbind最終的なものを取得するために使用できますdata.frame

df
#         Date          name score
# 1 12/09/2012 Mahesh\nRahul   120
# 2 13/09/2012 abc\nxyz\nrep   110

scan(text=as.character(df$name), what = "")
# Read 5 items
# [1] "Mahesh" "Rahul"  "abc"    "xyz"    "rep"  

cbind(df[rep(rownames(df), 
             sapply(gregexpr("\n", df$name), length)+1), 
         c("Date", "score")], 
      name = scan(text=as.character(df$name), what = ""))
#           Date score   name
# 1   12/09/2012   120 Mahesh
# 1.1 12/09/2012   120  Rahul
# 2   13/09/2012   110    abc
# 2.1 13/09/2012   110    xyz
# 2.2 13/09/2012   110    rep

read.table連結された列を分割するためにも機能します。

read.table(text = as.character(df$name), sep = "\n", header = FALSE)
#       V1
# 1 Mahesh
# 2  Rahul
# 3    abc
# 4    xyz
# 5    rep
于 2013-10-29T13:20:48.180 に答える