0

1列しかないデータフレームがあり、特定の行だけを選択して2列に変換したいのですが、ここで...お見せしましょう

これから行きたい

       V1   
1    one
2    two
3    &&three
4    four
5    &&five
6    six

これに

     V1      V2
1    one     NA
2    two     three
3    four    five
4    six     NA

したがって、a&&が付いているものは、上の行の右側の2列目に配置されます(それが理にかなっていることを願っています)。これを行う方法はありますか?

4

1 に答える 1

4

これが私のアプローチです:

データを読み込みます。

dat <- read.table(text="       V1   
1    one
2    two
3    &&three
4    four
5    &&five
6    six", head=T, stringsAsFactors = FALSE)

形を変える:

j <- grep("&&", dat$V1)                                 #find && rows
l <- j-1                                                #find rows above && rows
dat$V2 <- rep(NA, nrow(dat))                            #create NA vector
dat$V2[l] <- gsub("&&", "", dat[grep("&&", dat$V1), 1]) #see what it does :)
dat2 <- dat[-j, ]                                       #get rid of the && rows
rownames(dat2) <- 1:nrow(dat2)                          #rename rows

どちらが得られますか:

    V1    V2
1  one  <NA>
2  two three
3 four  five
4  six  <NA>
于 2012-04-26T15:20:21.323 に答える