2017-05-09 5 views
1

因子変数(リンゴまたはバナナのいずれか)を持つデータがあり、データセット内で値が1の場所を識別できるようにしたい2つの連続する行(すなわち、リンゴの場合は4行目、バナナの場合は行目の行4 & 5)の2つのオプションのうちの1つを使用します。複写された関数はここでは便利です(つまり、Index out the subsequent row with an identical value in R)が、私はカテゴリ変数で希望の出力を達成する方法についてはわかりません。次の行が同じ文字値を持つデータフレーム内の行を決定するR

例データ:

test = structure(list(cnt = c(87L, 51L, 24L, 69L, 210L, 21L, 15L, 9L, 
    12L), type = c("apple", "banana", "apple", "banana", "banana", 
    "apple", "banana", "apple", "apple")), .Names = c("cnt", "type" 
    ), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
    -9L), spec = structure(list(cols = structure(list(cnt = structure(list(), class = c("collector_integer", 
    "collector")), type = structure(list(), class = c("collector_character", 
    "collector"))), .Names = c("cnt", "type")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec")) 

所望の出力:

cnt type output 
1 87 apple FALSE 
2 51 banana FALSE 
3 24 apple FALSE 
4 69 banana TRUE 
5 210 banana TRUE 
6 21 apple FALSE 
7 15 banana FALSE 
8  9 apple TRUE 
9 12 apple TRUE 

私は、次のコードを使用し私は両方のリンゴとバナナが重複していることを私に告げる要約!:

を取得
test[!duplicated(test[,"type], fromLast=TRUE,] 

ご協力いただければ幸いです。

+0

'test%> mutate(出力=(タイプ==リード)タイプ、デフォルト=タイプ[n() - 1])|タイプ==遅延( type、default = type [2])) ' – akrun

答えて

2

だろう私たちは、ランレングス符号化を試すことができます。

x <- rle(test$type) 
x$values <- ifelse(x$lengths == 2, TRUE, FALSE) 

test$output <- inverse.rle(x) 
# > test 
# cnt type output 
# 1 87 apple FALSE 
# 2 51 banana FALSE 
# 3 24 apple FALSE 
# 4 69 banana TRUE 
# 5 210 banana TRUE 
# 6 21 apple FALSE 
# 7 15 banana FALSE 
# 8 9 apple TRUE 
# 9 12 apple TRUE 
+0

ありがとう! ifelseの単純な使い方のように。 – jjulip

2

これは複数の方法で実行できます。 1つのオプションはrleidからdata.tableであり、同じadjacenet要素に基づいてグループ化変数を作成し、次に論理条件の出力ie(:=)を割り当てることによって 'output'列を作成します。要素数が1(.N >1

library(data.table) 
setDT(test)[, output := .N>1, rleid(type)] 
test 
# cnt type output 
#1: 87 apple FALSE 
#2: 51 banana FALSE 
#3: 24 apple FALSE 
#4: 69 banana TRUE 
#5: 210 banana TRUE 
#6: 21 apple FALSE 
#7: 15 banana FALSE 
#8: 9 apple TRUE 
#9: 12 apple TRUE 

より大きい場合OPの説明に基づいて、tidyverseと1つのオプション

library(tidyverse) 
test %>% 
    mutate(output = (type == lead(type, default = type[n()-1]))| 
        type == lag(type, default = type[2])) 
+1

この2つのオプションに感謝します。非常に高く評価。私は両方の答えを受け入れることができたら幸いです。 – jjulip

関連する問題