3

私のデータセットには、オフセットされたデータを含む2つの列が含まれています-次のようなものです:

col1<-c("a", "b", "c", "d", "ND", "ND", "ND", "ND")
col2<-c("ND", "ND", "ND", "ND", "e", "f", "g", "h")
dataset<-data.frame(cbind(col1, col2))

これらの 2 つのオフセット列を、a から h までの文字のみを含む 1 つの列に結合したいと考えています。

私が考えているのは次のようなものですが、 rbind は正しいコマンドではありません。

dataset$combine<-rbind(dataset$col1[1:4], dataset$col2[5:8])
4

6 に答える 6

2

どうですか:

sel2 <- col2!="ND"
col1[sel2] <- col2[sel2]
> col1
[1] "a" "b" "c" "d" "e" "f" "g" "h"
于 2012-12-10T17:17:04.800 に答える
2

さらに別の方法として、 and を使用mapplygsubます。

 within(dataset, combine <- mapply(gsub, pattern='ND', replacement=col2, x=col1))
#   col1 col2 combine
# 1    a   ND       a
# 2    b   ND       b
# 3    c   ND       c
# 4    d   ND       d
# 5   ND    e       e
# 6   ND    f       f
# 7   ND    g       g
# 8   ND    h       h

@Andrieの回答に対するコメントによると、これによりNA行も保持されます。

于 2012-12-10T18:05:43.233 に答える
2

sapplyおよび無名関数を使用します。

dataset[sapply(dataset, function(x) x != "ND")]
# [1] "a" "b" "c" "d" "e" "f" "g" "h"
dataset$combine <- dataset[sapply(dataset, function(x) x != "ND")]
dataset
#   col1 col2 combine
# 1    a   ND       a
# 2    b   ND       b
# 3    c   ND       c
# 4    d   ND       d
# 5   ND    e       e
# 6   ND    f       f
# 7   ND    g       g
# 8   ND    h       h
于 2012-12-10T17:23:43.387 に答える
2

grep一致する要素を見つけて選択するために使用します。

c(col1[grep("^[a-h]$",col1)],col2[grep("^[a-h]$",col2)])
于 2012-12-10T17:23:55.077 に答える
1

別の観点:

transform(dataset, 
          combine=dataset[apply(dataset, 2, function(x) x %in% letters[1:8])])
  col1 col2 combine
1    a   ND       a
2    b   ND       b
3    c   ND       c
4    d   ND       d
5   ND    e       e
6   ND    f       f
7   ND    g       g
8   ND    h       h

dataset$combine <- dataset[apply(dataset,2, function(x) nchar(x)==1)] #Also works
于 2012-12-10T17:46:19.093 に答える
0

時には問題は十分に単純に考えることです... ;-)

dataset$combine<-c(dataset$col1[1:4], dataset$col2[5:8])
于 2012-12-10T17:18:19.280 に答える